PHP尝试创建一个能够同时添加多个元素而不覆盖的方法。

huangapple go评论67阅读模式
英文:

PHP Trying to create a method which could add several elements at same time without overwriting

问题

我正在尝试在类中创建一个包含一些用户信息的数组,主要问题是每个最后一个用户的名称都被下一个用户覆盖了,需要创建一个包含所有用户信息的数组。

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);

输出应该包含每个用户名。

英文:

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

答案1

得分: 4

为什么不只使用一个数组?

class User
{
    protected $name;
    public function __construct($name) {
        $this->name = $name;
    }
}

$users = [];
$users[] = new User('Jane');
$users[] = new User('Rick');
$users[] = new User('Niles');
英文:

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');

答案2

得分: 0

如果你想让一个对象拥有所有用户的列表,你必须将类属性转换为array类型
你可以像这样重构代码:

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);
英文:

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);

huangapple
  • 本文由 发表于 2023年6月15日 00:42:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76475821.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定