Home Backend Development PHP Tutorial php面向对象全攻略 (十一)__toString()用法 克隆对象 __call处_PHP

php面向对象全攻略 (十一)__toString()用法 克隆对象 __call处_PHP

Jun 01, 2016 pm 12:22 PM
tostring

16.__toString()方法
我们前面说过在类里面声明“— ”开始的方法名的方法(PHP 给我们提供的),都是在
某一时刻不同情况下自动调用执行的方法,“__toString()”方法也是一样自动被调用的,是在
直接输出对象引用时自动调用的, 前面我们讲过对象引用是一个指针,比如说:“$p=new
Person()”中,$p 就是一个引用,我们不能使用echo 直接输出$p,这样会输出“Catchable fatal
error: Object of class Person could not be converted to string”这样的错误,如果你在类里面定义
了“__toString()”方法,在直接输出对象引用的时候,就不会产生错误,而是自动调用了
“__toString()”方法,输出“__toString()”方法中返回的字符,所以“__toString()”方法一定
要有个返回值(return 语句)。
代码片段
复制代码 代码如下:
// Declare a simple class
class TestClass{
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
//定义一个__toString方法,返加一个成员属性$foo
public function __toString() {
return $this->foo;
}
}
$class = new TestClass('Hello');
//直接输出对象
echo $class;
?>

上例输出:Hello
17.克隆对象
有的时候我们需要在一个项目里面,使用两个或多个一样的对象,如果你使用“new”
关键字重新创建对象的话,再赋值上相同的属性,这样做比较烦琐而且也容易出错,所以要
根据一个对象完全克隆出一个一模一样的对象,是非常有必要的,而且克隆以后,两个对象
互不干扰。
在PHP5 中我们使用“clone”这个关键字克隆对象;
代码片段
复制代码 代码如下:

class Person{
//下面是人的成员属性
var $name; //人的名子
var $sex; //人的性别
var $age; //人的年龄
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值
function __construct($name="", $sex="", $age=""){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//这个人可以说话的方法, 说出自己的属性
function say() {
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."
";
}
}
$p1=new Person("张三", "男", 20);
//使用“clone”克隆新对象p2,和p1对象具有相同的属性和方法。
$p2=clone $p1;
$p2->say();
?>

PHP5 定义了一个特殊的方法名“__clone()”方法,是在对象克隆时自动调用的方法,
用“__clone()”方法将建立一个与原对象拥有相同属性和方法的对象,如果想在克隆后改变
原对象的内容,需要在__clone()中重写原本的属性和方法,“__clone()”方法可以没有参数,
它自动包含$this 和$that 两个指针,$this 指向复本,而$that 指向原本;
代码片段
复制代码 代码如下:
class Person{
//下面是人的成员属性
var $name; //人的名子
var $sex; //人的性别
var $age; //人的年龄
//定义一个构造方法参数为属性姓名$name、性别$sex和年龄$age进行赋值
function __construct($name="", $sex="", $age=""){
$this->name=$name;
$this->sex=$sex;
$this->age=$age;
}
//这个人可以说话的方法, 说出自己的属性
function say() {
echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."
";
}
//对象克隆时自动调用的方法, 如果想在克隆后改变原对象的内容,需要在__clone()中重写原本
的属性和方法
function __clone(){
//$this指的复本p2, 而$that是指向原本p1,这样就在本方法里,改变了复本的属性。
$this->name="我是假的$that->name";
$this->age=30;
}
}
$p1=new Person("张三", "男", 20);
$p2=clone $p1;
$p1->say();
$p2->say();
?>

上例输出:
执行结果
我的名子叫:张三性别:男我的年龄是:20
我的名子叫:我是假的张三性别:男我的年龄是:30
18.__call 处理调用错误
在程序开发中,如果在使用对象调用对象内部方法时候,调用的这个方法不存在那么程
序就会出错,然后程序退出不能继续执行。那么可不可以在程序调用对象内部不存在的方法
时,提示我们调用的方法及使用的参数不存在,但程序还可以继续执行,这个时候我们就要
使用在调用不存在的方法时自动调用的方法“__call()”。
代码片段
复制代码 代码如下:
//这是一个测试的类,里面没有属性和方法
class Test{
}
//产生一个Test类的对象
$test=new Test();
//调用对象里不存在的方法
$test->demo("one", "two", "three");
//程序不会执行到这里
echo "this is a test
";
?>

上例出现如下错误,程序通出不能继续执行;
Fatal error: Call to undefined method Test::demo()
下面我们加上“__call()”方法,这个方法有2 个参数,第一个参数为调用不存在的方法
过程中,自动调用__call()方法时,把这个不存在的方法的方法名传给第一个参数,第二个参
数则是把这个方法的多个参数以数组的形式传进来。
代码片段
复制代码 代码如下:
//这是一个测试的类,里面没有属性和方法
class Test{
//调用不存的方法时自动调用的方法,第一个参数为方法名,第二个参数是数组参数
function __call($function_name, $args){
print "你所调用的函数:$function_name(参数:";
print_r($args);
print ")不存在!
\n";
}
}
//产生一个Test类的对象
$test=new Test();
//调用对象里不存在的方法
$test->demo("one", "two", "three");
//程序不会退出可以执行到这里
echo "this is a test
";
?>

上例输出结果为:
执行结果
你所调用的函数: demo(参数:Array ( [0] => one [1] => two [2] => three ) )不存在!
this is a test.
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

See all articles