


Detailed explanation of PHP object-oriented magic methods (__tostring, __invoke)
Objectives of this article:
1. Understand the definition of magic methods in PHP
2. Understand the usage scenarios of __tostring() magic method
3. Master the usage of __tostring() magic method
4. Understand the usage scenarios of __invoke() magic method
5. Master the usage of __invoke() magic method
(1) Understand the definition of magic methods in PHP
PHP Reserve all class methods starting with __ (two underscores) as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.
(2) Understand the usage scenarios of the __tostring() magic method
When we need to convert an object into a string, we can define the __tostring method in the class, and then write our custom logic in it
(3) Master the magic method of __tostring() Usage
Summary:
1. The definition of the magic method __tostring method in the class, the definition format is as follows public function __tostring(), note that there are two underscores, not one
2. When the object is used as a String, this method will be automatically called
- For example, when we generally output a string, we use echo "Hello", so if we want to convert an object When used as String, we can also directly write echo $obj like this. At this time, this line of code will trigger the execution of the __tostring magic method
Each summary is passed It comes from practice. Now we use practice to demonstrate the summary. This can promote understanding and make each summary clearer and more intuitive.
##Case 1.
Practice goals:
1. In the class, The definition of the magic method __tostring method, the definition format is as follows public function __tostring(), note that there are two underscores, not one
The specific code is as follows:
<?php class Animal{ public $name = ""; public function __construct($name){ $this->name = $name; } public function eat(){ } public function sleep(){ } //魔术方法 public function __tostring(){ return "自动执行了Animal类中的__tostring方法<br/>"; } } $monkey = new Animal("猴子"); ?>
Case 2,
Practice goals:
##2. When the object is used as a String, this method will be automatically called
-for example We usually output strings using echo "Hello", so if we want to use an object as a String, we can also directly write echo $obj like this. At this time, this line of code will trigger the __tostring magic. Execution of the method
The specific code is as follows: <?php
class Animal{
public $name = "";
public function __construct($name){
$this->name = $name;
}
public function eat(){
}
public function sleep(){
}
//魔术方法
public function __tostring(){
return "自动执行了Animal类中的__tostring方法<br/>";
}
}
$monkey = new Animal("猴子");
echo $monkey;
?>
The operation result is:
Automatic execution The __tostring method in the Animal class
我们发现其实我们没有手动的去调用__tostring方法,也就是说没有写成$monkey->__tostring(),但是这个方法依然执行了,因为什么呢?因为我们写了echo $monkey,所以相当于我们把$monkey对象当成了字符串来使用了,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了
这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试
具体代码如下:
<?php class Animal{ public $name = ""; public function __construct($name){ $this->name = $name; } public function eat(){ } public function sleep(){ } //魔术方法 注意这里改成了一个下划线 public function _tostring(){ return "自动执行了Animal类中的__tostring方法<br/>"; } } $monkey = new Animal("猴子"); echo $monkey; ?>
运行结果为:
Catchable fatal error: Object of class Animal could not be converted to string in D:\E-class\class-code\classing\index.php on line 19
所以此刻就会报错了,因为没有__tostring的魔术方法了,所以一定要注意是2个下划线,就好像构造函数和析构函数一样,都是两个下划线
(四)、了解__invoke()魔术方法的使用场景
当我们有需要将一个对象直接当成方法使用时,我们可以在类中定义__invoke方法,然后在里面写我们的自定义逻辑
(五)、掌握__invoke()的魔术方法的用法
总结:
1、类中__invoke魔术方法的定义如下:public function __invoke()其实和普通函数一样的定义,就是名称必须是__invoke
2、当对象被当做方法使用时,这个方法会被自动调用
-比如我们一般调用方法是怎么调用的,是直接方法名(),比如smile()这样,所以当我们希望把一个对象当成方法使用时,应该怎么做呢?其实就是直接$obj(里面可以写参数),这样的形式就是方法调用的形式对吧,那么,一旦我们这样写$obj(参数),那么这个类中的__invoke()的魔术方法也会被自动的调用
每个总结都是通过实践得出来的,现在我们用实践来演示总结,这样可以促进理解,让每个总结理解起来更加清晰,直观
具体代码:
案例一、
实践目标:
1、类中__invoke魔术方法的定义如下:public function __invoke()其实和普通函数一样的定义,就是名称必须是__invoke
具体代码如下:
<?php class Animal{ public $name = ""; public function __construct($name){ $this->name = $name; } public function eat(){ } public function sleep(){ } //魔术方法 public function __invoke(){ return "自动执行了Animal类中的__invoke方法<br/>"; } } $monkey = new Animal("猴子"); ?>
案例二、
实践目标:
1、当对象被当做方法使用时,这个方法会被自动调用
-比如我们一般调用方法是怎么调用的,是直接方法名(),比如smile()这样,所以当我们希望把一个对象当成方法使用时,应该怎么做呢?其实就是直接$obj(里面可以写参数),这样的形式就是方法调用的形式对吧,那么,一旦我们这样写$obj(参数),那么这个__invoke()的魔术方法也会自动的调用
具体代码如下:
<?php class Animal{ public $name = ""; public function __construct($name){ $this->name = $name; } public function eat(){ } public function sleep(){ } //魔术方法 public function __invoke(){ echo "自动执行了Animal类中的__invoke方法<br/>"; } } $monkey = new Animal("猴子"); $monkey(); ?>
运行结果如下:
自动执行了Animal类中的__invoke方法
我们发现其实我们没有手动的去调用__invoke方法,也就是说没有写成$monkey->__invoke(),但是这个方法依然执行了,因为什么呢?因为我们写了$monkey(),所以相当于我们把$monkey对象当成方法来使用了,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了
这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试
<?php class Animal{ public $name = ""; public function __construct($name){ $this->name = $name; } public function eat(){ } public function sleep(){ } //魔术方法 只写一个_试下 public function _invoke(){ echo "自动执行了Animal类中的__invoke方法<br/>"; } } $monkey = new Animal("猴子"); $monkey(); ?>
运行结果如下:
Fatal error: Uncaught Error: Function name must be a string in D:\E-class\class-code\classing\index.php:19 Stack trace: #0 {main} thrown in D:\E-class\class-code\classing\index.php on line 19
所以一定要注意是2个下划线,不是一个,否则就不是魔术方法了
总结:
1、本文主要是讲解了2个魔术方法,__tostring,__invoke,并具体讲了他们的具体实现方式和使用场景
希望本文能给大家带来一定的帮助,谢谢!!!
The above is the detailed content of Detailed explanation of PHP object-oriented magic methods (__tostring, __invoke). For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft