PHP 间接修改重载属性

发布于 2024-09-26 04:29:19 字数 595 浏览 0 评论 0原文

我有这个简单的类:

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;) 它会起作用?

i have this simple class:

class A
{
    var $children=array();

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

By accessing the "firstChild" property it should return its first child by reference or null if there are no children.

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

Now if the class contains at least one child it works great but if it doesn't (and it should return null) it triggers the error "Indirect modification of overloaded property".

Why does this happen? I'm not trying to modify anything so what is that "Indirect modification"? And why if i remove the reference sign ($c=$a->firstChild;) it works?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

演出会有结束 2024-10-03 04:29:19

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

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

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

I think you should use empty() instead of count(). One reason for that is (quote from manual for count())

If var is not an array or an object with implemented Countable interface, 1 will be returned. There is one exception, if var is NULL, 0 will be returned.

Also, if you're storing objects in this array, you don't have to use references, since (in PHP 5+) objects are passed reference by default.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文