如果__set没有被调用,__get不会被调用,但是代码有效吗? [英] __get is not called if __set is not called, however code works?

查看:127
本文介绍了如果__set没有被调用,__get不会被调用,但是代码有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的代码:

 <?php 

class SampleClass {

公共函数__get($ name){
echoget called;
echo $ name;
}

public function __set($ name,$ value){
echoset called;
}

}

?>

以及我的索引档:

  $ object = new SampleClass(); 
$ object-> color =black;
echo $ object-> color;

如果我按照原样运行此代码,则输出如下:

 set calledget calledcolor 

然而,如果我评论

  public function __set($ name,$ value){
echoset called;
}

上面的部分(仅此部分),则输出为:

黑色

那么这里发生了什么?

解决方案

这是对正在发生的事情的解释。在你的第一个例子中。您从未将值存储在对象中,也没有声明的属性存在。这个 echo $ object-> color; 从来没有做任何事情,因为没有任何东西从 __ get 返回。



在第二个示例中,您为对象中的属性分配了一个值。由于您未在对象中声明该属性,因此默认情况下会将其创建为公共。由于它的公开,访问它时从不会调用 __ get


Here is my code:

<?php

class SampleClass {

    public function __get($name){
        echo "get called";
        echo $name;
    }

    public function __set($name, $value) {
        echo "set called";
    }

}

?>

And my index file:

$object = new SampleClass();
$object->color = "black";
echo $object->color;

If I run this code as it is, here is the output:

set calledget calledcolor

However if I comment out

public function __set($name, $value) {
    echo "set called";
}

the part above (only this part), then the output will be:

black

So what happened here?

解决方案

This is an explanation of what is happening. In your first example. You never stored the value within the object, nor did a declared property exist. This, echo $object->color; never actually does anything as nothing is returned from __get.

In your second example, you assigned a value to a property in your object. Since you did not declare the property in your object, it gets created by default as public. Since its public, __get is never called when accessing it.

这篇关于如果__set没有被调用,__get不会被调用,但是代码有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆