Home > Backend Development > PHP Tutorial > 基础题:对象引用问题?

基础题:对象引用问题?

WBOY
Release: 2016-06-23 14:38:25
Original
823 people have browsed it

<?php$global_obj=null;class Demo{	var $my_val;	public function __construct(){		global $global_obj;		$global_obj=&$this;	}}$p=new Demo();$p->my_val=5;global $global_obj;$global_obj->my_val=10;echo $p->my_val;  //输出5var_dump($p===$global_obj);  //返回false?>
Copy after login


请问为什么结果是5 而不是10;
我的理解是:PHP5中,除非你用clone关键字明确要克隆一个对象,否则将永远不会无意识地复制对象。
这样理解对吗?


回复讨论(解决方案)

第 8 行 $global_obj=&$this; 时,
第 18 行会有
Creating default object from empty value (从空值创建默认对象)
的警告,你把错误信息屏蔽了,所以搞不清为什么了

当第 8 行纠正为 $global_obj = $this; 时
就能输出 10 了

推荐看下 http://php.net/manual/zh/language.oop5.references.php

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template