英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论