


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;
?>
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!

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to use Go language to implement object-oriented event-driven programming Introduction: The object-oriented programming paradigm is widely used in software development, and event-driven programming is a common programming model that realizes the program flow through the triggering and processing of events. control. This article will introduce how to implement object-oriented event-driven programming using Go language and provide code examples. 1. The concept of event-driven programming Event-driven programming is a programming model based on events and messages, which transfers the flow control of the program to the triggering and processing of events. in event driven

The @JsonIdentityInfo annotation is used when an object has a parent-child relationship in the Jackson library. The @JsonIdentityInfo annotation is used to indicate object identity during serialization and deserialization. ObjectIdGenerators.PropertyGenerator is an abstract placeholder class used to represent situations where the object identifier to be used comes from a POJO property. Syntax@Target(value={ANNOTATION_TYPE,TYPE,FIELD,METHOD,PARAMETER})@Retention(value=RUNTIME)public

Go language supports object-oriented programming through type definition and method association. It does not support traditional inheritance, but is implemented through composition. Interfaces provide consistency between types and allow abstract methods to be defined. Practical cases show how to use OOP to manage customer information, including creating, obtaining, updating and deleting customer operations.

Analyzing the Flyweight Pattern in PHP Object-Oriented Programming In object-oriented programming, design pattern is a commonly used software design method, which can improve the readability, maintainability and scalability of the code. Flyweight pattern is one of the design patterns that reduces memory overhead by sharing objects. This article will explore how to use flyweight mode in PHP to improve program performance. What is flyweight mode? Flyweight pattern is a structural design pattern whose purpose is to share the same object between different objects.

The Go language supports object-oriented programming, defining objects through structs, defining methods using pointer receivers, and implementing polymorphism through interfaces. The object-oriented features provide code reuse, maintainability and encapsulation in the Go language, but there are also limitations such as the lack of traditional concepts of classes and inheritance and method signature casts.

OOP best practices in PHP include naming conventions, interfaces and abstract classes, inheritance and polymorphism, and dependency injection. Practical cases include: using warehouse mode to manage data and using strategy mode to implement sorting.

There is no concept of a class in the traditional sense in Golang (Go language), but it provides a data type called a structure, through which object-oriented features similar to classes can be achieved. In this article, we'll explain how to use structures to implement object-oriented features and provide concrete code examples. Definition and use of structures First, let's take a look at the definition and use of structures. In Golang, structures can be defined through the type keyword and then used where needed. Structures can contain attributes

By mastering tracking object status, setting breakpoints, tracking exceptions and utilizing the xdebug extension, you can effectively debug PHP object-oriented programming code. 1. Track object status: Use var_dump() and print_r() to view object attributes and method values. 2. Set a breakpoint: Set a breakpoint in the development environment, and the debugger will pause when execution reaches the breakpoint, making it easier to check the object status. 3. Trace exceptions: Use try-catch blocks and getTraceAsString() to get the stack trace and message when the exception occurs. 4. Use the debugger: The xdebug_var_dump() function can inspect the contents of variables during code execution.
