skip to Main Content

I’m trying to create an array in class, which will contain some users info,the main problem is that every last users name is overwrited by the next one, need to create an array which contain all of them.

class Users{
    public $name;
    function add($name){
        $this -> name = $name;
    }
    
}

$users = new Users();
$users->add('Jane');
$users->add('Rick');
$users->add('Niles');

var_dump($users);

output should contain each username

2

Answers


  1. Why not just use an array?

    class User
    {
        protected $name;
        public function __construct($name) {
            $this->name = $name;
        }
    }
    
    $users = [];
    $users[] = new User('Jane');
    $users[] = new User('Rick');
    $users[] = new User('Niles');
    
    Login or Signup to reply.
  2. if you want an object to have a list of all users, you must convert the class attribute to array type
    you can refactor the code like this

    class Users{
        public $names = array();
        function add($name){
            $this->names[] = $name;
        }
        
    }
    
    $users = new Users();
    $users->add('Jane');
    $users->add('Rick');
    $users->add('Niles');
    
    var_dump($users);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search