PHP5 的对象赋值机制介绍_php技巧

WBOY
Release: 2016-05-17 09:16:34
Original
1269 people have browsed it
复制代码代码如下:

class SimpleClass{
public $var = 'a default value';
public function displayVar() {
echo $this->var;
}
}
$instance = new SimpleClass();
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; // $instance and $reference become null var_dump($instance);var_dump($reference);var_dump($assigned);
var_dump($instance);
var_dump($assigned);
var_dump($reference);
?>

php5 改写了OOP底层。当类生成一个实例(对象)的时候,返回值$instance并不是对象本身,而只是对象的一个id(或者资源句柄),所以,当$instance被赋值给$assigned的时候,$assigned也指向了这个对象,这有点像普通变量的引用(&)操作。所以,当对$instance初始化的时候,$assigned也被初始化了。但是,当$instance被销毁(=null)的时候,因为对应的对象还有一个句柄存在($assigned),所以对象并不会被销毁,析构函数也不会被触发。结果,var_dump($assigned)是对象的值,而$instance已经是空句柄,显示null。$reference因为与$instance有类似普通变量间的引用关系,所以也成为空句柄,显示 null。
Related labels:
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!