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

时间:2012-07-13 12:36:30

标签: php arrays class object

我可以在php中为不存在或不存在的成员自由分配内容吗?成员名称和关联数组索引之间有什么区别吗?

我之间有任何区别

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

 $a->foo = 'something';

如果存在差异,那么如何创建“空”对象并动态添加成员呢?

3 个答案:

答案 0 :(得分:8)

您正在混合Arrays(数据包/容器)和Objects(它们是具有语义含义和功能的数据包装)。

阵列访问

第一个是正确的,因为您使用的数组在其他语言中的行为类似于HashTableDictionary

$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 Magic

但是仍然可以选择使用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

这有望帮助您解决问题。

答案 1 :(得分:3)

如果你想像在关联数组上那样为对象分配任意成员,你可能想要研究PHP的魔法property overloading

这是一个允许您分配和检索变量的示例类(主要来自PHP文档):

<?php
class PropertyTest
{
    /**  Location for overloaded data.  */
    private $data = array();

    public function __set($key, $value) {
        $this->data[$key] = $value;
    }

    public function __get($key) {
        return $this->data[$key];
    }
}
// sample use:
$a = new PropertyTest();
$a->foo = "bar";

echo $a->foo; // will print "bar"
?>

答案 2 :(得分:2)

您可以创建一个空的类对象,然后向其中添加属性,例如:

<?php
$myObject = new StdClass();
$myObject->id = 1;
$myObject->name = "Franky";
$myObject->url = "http://www.google.com";
var_dump($myObject);

......这应该产生

object(stdClass)#1 (3) { ["id"]=> int(1) ["name"]=> string(6) "Franky" ["url"]=> string(21) "http://www.google.com" }

就个人而言,我更喜欢使用对象类而不是数组。