【问题标题】:PHP Indirect modification of overloaded propertyPHP间接修改重载属性
【发布时间】:2010-10-06 14:19:33
【问题描述】:

我有这个简单的课程:

class A
{
    var $children=array();

    function &__get($name)
    {
        if($name==="firstChild")
        {
            if(count($this->children)) $ret=&$this->children[0];
            else $ret=null;
        }
        return $ret;
    }
}

通过访问“firstChild”属性,它应该通过引用返回其第一个孩子,如果没有孩子,则返回 null。

$a=new A;
$c=&$a->firstChild;

现在,如果该类至少包含一个子类,它工作得很好,但如果它不包含(并且它应该返回 null)它会触发错误“间接修改重载属性”。

为什么会这样?我不想修改任何东西,那么“间接修改”是什么?为什么如果我删除参考符号 ($c=$a->firstChild;) 它会起作用?

【问题讨论】:

    标签: php class properties overloading


    【解决方案1】:

    我认为您应该使用empty() 而不是count()。原因之一是(引用count() 的手册)

    如果 var 不是数组或实现了 Countable 接口的对象,则返回 1。有一个例外,如果 var 为 NULL,则返回 0。

    此外,如果您在此数组中存储对象,则不必使用引用,因为(在 PHP 5+ 中)对象默认传递引用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 2020-03-24
      • 1970-01-01
      相关资源
      最近更新 更多