<?php class Person { private $name; private $age; private $id; function __construct( $name, $age ) { $this->name = $name; $this->age = $age; } function setId( $id ) { $this->id = $id; } function __clone() { // 克隆时候执行 $this->id = 0; } } $person = new Person( "bob", 44 ); $person->setId( 343 ); $person2 = clone $person; print_r( $person ); print_r( $person2 ); ?>
输出:
Person Object ( [name:Person:private] => bob [age:Person:private] => 44 [id:Person:private] => 343 ) Person Object ( [name:Person:private] => bob [age:Person:private] => 44 [id:Person:private] => 0 )
再看一个例子
<?php class Account { // 账户类 public $balance; // 余额 function __construct( $balance ) { $this->balance = $balance; } } class Person { private $name; private $age; private $id; public $account; function __construct( $name, $age, Account $account ) { $this->name = $name; $this->age = $age; $this->account = $account; } function setId( $id ) { $this->id = $id; } function __clone() { $this->id = 0; } } $person = new Person( "bob", 44, new Account( 200 ) ); // 以类对象作为参数 $person->setId( 343 ); $person2 = clone $person; // give $person some money $person->account->balance += 10; // $person2 sees the credit too print $person2->account->balance; // person的属性account也是一个类,他的属性balance的值是210 // output: // 210 ?>
点评:学习还是能够开拓大脑的,今天终于明白为什么有多个箭头的概念了$person->account->balance。这里的account属性是一个对象。
__toString
<?php class Person { function getName() { return "Bob"; } function getAge() { return 44; } function __toString() { $desc = $this->getName()." (age "; $desc .= $this->getAge().")"; return $desc; } } $person = new Person(); print $person; // 打印时候集中处理 // Bob (age 44) ?>
点评:必须是print或echo时才有效,print_r就输出对象。
Person Object()
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP数组(Array)操作技巧大全》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》