PHP魔术方法__clone()

2018-09-18 15:00 By "Powerless" 3298 0 1

PHP中可以使用clone关键字来复制对象

示例代码如下:

$copy_of_object = clone $object;

但是,clone关键字只会进行浅复制,所有引用的属性依然会指向原来的变量。

如果对象里定义了__clone()方法,那么复制时就会调用__clone()方法,从而允许我们修改被复制的值(如果需要的话)。

示例代码如下:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex='Male')
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __clone()
    {
        echo __METHOD__."your are cloning the object.<br>";
    }
}
$person = new Person('John'); // 赋初始值
$person2 = clone $person;
var_dump('persion1:');
var_dump($person);
echo '<br>';
var_dump('persion2:');
var_dump($person2);

输出结果如下:

Person::__clone your are cloning the object.
string(9) "persion1:" object(Person)#1 (3) { ["sex"]=> string(3) "Male" ["name"]=> string(6) "John" ["age"]=> int(25) }
string(9) "persion2:" object(Person)#2 (3) { ["sex"]=> string(3) "Male" ["name"]=> string(6) "John" ["age"]=> int(25) }


评 论

View in WeChat

Others Discussion

  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • MySQL分组
    Posted on 2019-11-18 14:00
  • PHP练习-爬楼梯问题
    Posted on 2020-08-14 23:56
  • PHP8.1 性能基准测试
    Posted on 2022-10-08 17:40
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 必学十大经典排序算法,看这篇就够了
    Posted on 2019-11-18 16:30
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • PHP练习-无重复字符的最长子串
    Posted on 2020-09-17 18:03