Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
第二个类在不返回或使用引用PHP OOP的情况下更改第一个类_Php_Class_Oop_Properties_Namespaces - Fatal编程技术网

第二个类在不返回或使用引用PHP OOP的情况下更改第一个类

第二个类在不返回或使用引用PHP OOP的情况下更改第一个类,php,class,oop,properties,namespaces,Php,Class,Oop,Properties,Namespaces,我有两门课。我对第二个类如何编辑第一个类的属性而不将第一个类作为引用传递感到困惑 first.php second.php 我得到这个输出: second value 有人能解释一下第二节课是怎么做的吗?在PHP中,默认情况下,对象是通过引用传递的。在本例中,首先将类对象传递给第二个类对象。因此PHP为您完成了这项工作,您不必指定通过引用传递它,例如&$variable,因为$this是一个对象而不是变量。如果要传递$variable,则必须指定是否要通过引用$second->metho

我有两门课。我对第二个类如何编辑第一个类的属性而不将第一个类作为引用传递感到困惑

first.php

second.php

我得到这个输出:

second value

有人能解释一下第二节课是怎么做的吗?在PHP中,默认情况下,对象是通过引用传递的。在本例中,首先将类对象传递给第二个类对象。因此PHP为您完成了这项工作,您不必指定通过引用传递它,例如&$variable,因为$this是一个对象而不是变量。如果要传递$variable,则必须指定是否要通过引用$second->method&$variable传递它

call_user_func_array(array(new $second, 'method'), array($this));

在那个调用中,您将$this作为class second中方法的参数传递,并修改属性prop。

正如Elin所建议的,请阅读。它回答了所有问题

从PHP5开始,对象变量不再包含对象本身作为值。它只包含一个允许对象访问器查找实际对象的对象标识符。当一个对象通过参数发送、返回或分配给另一个变量时,不同的变量不是别名:它们持有指向同一对象的标识符副本


此函数正在发挥作用

call_user_func_array()
这是回调函数:-call\u user\u func\u array-使用参数数组调用回调

function __construct(){
        $second = '\\second\\second';
        require 'second.php';
         //This is the call back function which 
        call_user_func_array(array(new $second, 'method'), array($this));
    }

    call_user_func_array(array(new $second, 'method'), array($this));
此函数有两个参数,arraynew$second,'method',array$This 在第一个参数中,有一个由两个元素组成的数组,即new$second和'method',后者实例化了类new second和函数方法。第二个参数是

array($this) which says this class, meaning or referring to `class first {}`
简而言之,第一个类可以修改的原因是它有一个带有第二个类参数的回调函数


您可以查看is函数是如何工作的

对象通过引用传递是一个简单的版本,尽管它不像看上去那么简单。这是启动@Elin的一个很好的源代码,所以我不必通过引用来传递它,php为我做了这个吗?@Elin谢谢。这本书很有帮助。谢谢。我读过Elin建议的链接。在那一页中,它提到了一个常见的误解,即,正如您所说,“对象是通过引用传递的”。相反,$this或任何其他对象引用的是指针,而不是数据本身。这意味着指针被复制而不是数据,因此两者同时更新。作为澄清。虽然这可以回答问题,但最好在此处提供实际信息,而不仅仅是链接。
function __construct(){
        $second = '\\second\\second';
        require 'second.php';
         //This is the call back function which 
        call_user_func_array(array(new $second, 'method'), array($this));
    }

    call_user_func_array(array(new $second, 'method'), array($this));
array($this) which says this class, meaning or referring to `class first {}`