gpt4 book ai didi

php - 我可以在php中自由设置成员吗?

转载 作者:行者123 更新时间:2023-12-02 05:43:37 24 4
gpt4 key购买 nike

我可以在 php 中自由分配一些东西给不存在的或未知存在的成员吗?成员名称和关联数组索引之间有什么区别吗?

我之间有什么区别

$a = array();
$a['foo'] = 'something';

 $a->foo = 'something';

如果有区别,那么我如何创建“空”对象并动态地向其添加成员?

最佳答案

你在混Arrays (这是用于数据的袋子/容器)和 Objects (这是对具有语义和功能的数据的包装)。

数组访问

第一个是正确的,因为您使用的数组类似于 HashTable。或 Dictionary用其他语言。

$a = array();               // create an empty "box"
$a['foo'] = 'something'; // add something to this array

对象访问

第二个是对象访问。你会使用这样的东西:

class Foo {
public $foo;
}

$a = new Foo();
$a->foo = 'something';

虽然在这种情况下更好的用法是使用像这样的 setter/getter 方法。

class Foo {
private $foo;
public function setFoo($value) {
$this->foo = $value;
}
public function getFoo() {
return $this->foo;
}
}

$a = new Foo();
$a->setFoo('something');
var_dump($a->getFoo());

PHP 魔法

但是仍然可以选择使用 PHPs Magic Methods创造一个你描述的行为。然而,这不应被视为将数据存储到对象的通常方式,因为这会导致错误并使您在(单元)测试时更加困难。

class Foo {
private $data = array();
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __get($key) {
return $this->data[$key];
}
}

$a = new Foo();
$a->foo = 'something'; // this will call the magic __set() method
var_dump($a->foo) // this will call the magic __get() method

希望这能帮助您解决问题。

关于php - 我可以在php中自由设置成员吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11470655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com