首页 > 开发 > PHP > 正文

PHP对象相关知识总结

2024-05-04 22:48:10
字体:
来源:转载
供稿:网友

对象传递:一种说法是“PHP对象是通过引用传递的”,更准确的说法是别名(标识符)传递,即它们都保存着同一个标识符(ID)的拷贝,这个标识符指向同一个对象的真正内容。

 <?php class A {   public $foo = 1; }   $a = new A; $b = $a;   // $a ,$b都是同一个标识符的拷贝       // ($a) = ($b) = <id> $b->foo = 2; echo $a->foo."/n";//2 $c = new A; $d = &$c;  // $c ,$d是引用       // ($c,$d) = <id>  $d->foo = 2; echo $c->foo."/n";//2  $e = new A;  function foo($obj) {   // ($obj) = ($e) = <id>   $obj->foo = 2; }  foo($e); echo $e->foo."/n";//2

•对象复制:对象复制可以通过 clone 关键字来完成,如果原对象定义了 __clone() 方法,则新对象中的 __clone() 方法将在复制完后被调用,__clone() 方法可用于修改复制对象属性的值。当对象被复制后,会对对象的所有属性执行一个浅复制(shallow copy),但所有的引用属性仍然会是一个指向原来的变量的引用。

 <?php class SubObject {   static $instances = 0;   public $instance;    public function __construct()   {     $this->instance = ++self::$instances;   }    public function __clone()   {     $this->instance = ++self::$instances;   } }  class MyCloneable {   public $object1;   public $object2;    function __clone()   {     // 强制复制一份this->object, 否则仍然指向同一个对象     $this->object1 = clone $this->object1;   }      function cloneTest()   {     echo 'cloneTest';   } }  $obj = new MyCloneable();  $obj->object1 = new SubObject(); $obj->object2 = new SubObject();  $obj2 = clone $obj;  print("Original Object:/n"); print_r($obj);  print("Cloned Object:/n"); print_r($obj2); echo $obj2->cloneTest().":/n"; echo (new Reflectionclass($obj2));

上例输出结果:

Original Object:MyCloneable Object(  [object1] => SubObject Object    (      [instance] => 1    )  [object2] => SubObject Object    (      [instance] => 2    ))Cloned Object:MyCloneable Object(  [object1] => SubObject Object    (      [instance] => 3    )  [object2] => SubObject Object    (      [instance] => 2    ))cloneTest:Class [ <user> class MyCloneable ] { @@ /public/t.php 18-33 - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [2] {  Property [ <default> public $object1 ]  Property [ <default> public $object2 ] } - Methods [2] {  Method [ <user> public method __clone ] {   @@ /public/t.php 23 - 27  }  Method [ <user> public method cloneTest ] {   @@ /public/t.php 29 - 32  } }}

•对象遍历: foreach只能遍历对象的可见属性,无法遍历其方法,实现起来比较容易;另外,也可通过实现Iterator接口或IteratorAggregate接口的方法遍历对象属性。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表