您可以通过将该值分配给它的引用来将值注入PHP对象

时间:2012-09-12 22:26:33

标签: php reference tostring

这就是我想要做的事情:

$var = new ObjectICreated("yay");
echo $var; // outputs "yay" via the __toString() magic method
$var = "Boo"; // $var is still a ObjectICreated, but will now output "Boo" from __toString()
我疯了吗?我认为SimpleXML做了这件事,但我不确定如何。有什么想法吗?

推理:我想跟踪特定对象的更改,而不必使用数十亿的getter / setter。

好的,感谢您对后代的评论。 SimpleXML会这样做。以下工作基于http://www.php.net/manual/en/simplexml.examples-basic.php示例#9。

中的代码
$x = simplexml_load_string($xml); // xml from example #9
// Pre-reference value
print_r($x->movie[0]->characters->character[0]->name);  
// Assign to reference of a SimpleXMLElement
$x->movie[0]->characters->character[0]->name = 'Miss Coder';
print_r($x->movie[0]->characters->character[0]->name);

输出如下:

SimpleXMLElement Object ( [0] => Ms Coder ) 
SimpleXMLElement Object ( [0] => Miss Coder )

正如你所看到的,它仍然是一个SimpleXMLElement,就像在分配“Miss Coder”之前一样。

再次感谢大家的时间。

3 个答案:

答案 0 :(得分:2)

正如@dbf所说

  无论什么

$var = "Boo"都会覆盖$ var

如果你想避免使用getter / setter,你可以简单地公开一个公共成员

$var = new ObjectICreated("yay");
echo $var; // outputs "yay" from $var->value via the __toString() magic method
$var->value = "Boo";

答案 1 :(得分:2)

如果你想阻止很多setter / getters你可以实现魔术设置器/ getter。虽然这通常是代码味道。

class Foo
{
    private $magicData = array();

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

    public function __get($name)
    {
        return $this->magicData[$name];
    }
}

现在您只需执行以下操作:

$foo = new Foo();
$foo->something = 'bar';
$foo->reallyAnything = 'baz';

echo $foo->something;

答案 2 :(得分:0)

感谢所有回复的人。我能够提出一个适合我需要的解决方案。

在我到达那里之前,正如@PeeHaa所述,__ get和__set魔术方法是这里的方法。但是,为了达到原始帖子的既定目标,我们需要一个对象层次结构。据我所知,这就是SimpleXML能够完成我在原始帖子和后续编辑中描述的内容,@ PeeHaa在评论中再次提到。我最初的想法确实是不可能的[深深的遗憾]。

下面是我要完成此任务的非常原始的观点。我做了一些前期工作,似乎按预期工作。显然,我将填写此内容并对其进行改进以满足我的特定需求。为简洁起见,它也缺少一些子对象创建代码和子类型智能。

class Foo { 
    protected $_value;
    protected $children = array();
    public function __construct($value) {
        $this->_value = $value;
    }
    public function setValue($value) {
        $this->_value = $value;
    }
    public function __toString() {
        return $this->_value;
    }
    public function __set($key, $value) {
        if(isset($this->children[$key]) == false) {
            $this->children[$key] = new self($value);
        } else {
            $this->children[$key]->setValue($value);
        }
    }
    public function __get($key) {
        return $this->children[$key];
    }
}

$foo = new Foo("");
$foo->myVar = "some value"; // assigns "some value" to $foo->myValue->_value
print_r($foo->myVar); // outputs that we have a Foo
echo $foo->myVar; // outputs the contents of $foo->myValue->_value aka "some value"

// This works and produces the string value of both "myVar" and "anotherVar",
// with "anotherVar" being an instance of Foo.
$foo->myVar->anotherVar = "some other value";

再次感谢大家的贡献和耐心,因为我已经解决了这个问题。