新对象模型

PHP 5 中有个新对象模型(Object Model)。PHP 处理对象的方式完全重写了,允许更佳性能和更多特性。之前版本的 PHP,对象处理方式和原始类型(例如整型和字符串)相同。此方法的缺点是当变量被赋值或作为参数传递给方法时语义上整个对象都被拷贝。在新方法中,对象通过句柄引用,而不是值(可以将句柄当成是对象的标识符)。

很多 PHP 程序员根本没意识到旧的对象模型的这种拷贝怪癖,因此大多数 PHP 应用程序拿来就能运行,或者只做很小的修改。

新对象模型的文档见语言参考

与 PHP 4 的兼容性参见 zend.ze1_compatibility_mode

User Contributed Notes

zzo38 07-Oct-2007 05:06
You should be able to clone a object in compatibility of PHP4,PHP5 with:
<?php
 $x
=unserialize(serialize($y));
?>
bdas at premiergroup dot uk dot com 25-May-2007 04:49
Since PHP5 upgraded PHP to an OOP language, they CHANGED the metaphor so that when you copy an object, you just get a pointer to it (as in C# and Java) and so therefore they needed to make a way to CLONE objects as well in case you need a REAL copy of the object.

Most cases, clone is not needed, simply because a real copy of an object is usually not mandatory.  In special cases, object cloning can be used to save time in porting.
quinn at strangecode dot com 19-May-2006 05:53
Here is another possible solution for migrating code to php 5 when using $this = 'something' reassignments. In my case, I had several classes  with methods that were self-instantiating with static calls. I was able to simply use a different variable: I changed $this to $_this and it worked the same because I copied an instance of the original object by reference using an instantiation factory method:

class DB {
    function &getInstance()
    {
        static $instance = null;

        if ($instance === null) {
            $instance = new DB();
        }

        return $instance;
    }
    ...

In every method needing access to this object I assigned it to a temporary variable by reference:
   
    function doSomething ()
    {
        $_this =& DB::getInstance();

        $_this->doSomethingElse();
        $_this->param['id'] = 123;
    }

Which allows method calls or saving data back to the original object.

I originally created classes like this so I didn't need to keep track of instantiations or global objects. I could just call DB::doSomething() and the object is created dynamically or referenced from an already existing object.