search
HomeBackend DevelopmentPHP TutorialDetailed explanation of magic functions in PHP object-oriented development_PHP tutorial

Magic functions in PHP include tostring, call, clone, and autoload. I hope this tutorial will be helpful to all my friends.

Summary of object-oriented development

1. Description and configuration of objects. (can be understood as the output text description of the object)
2. A processing of object method. (It can be understood as customizing a more humane error message when an exception occurs)
3. Application of cloned objects. (It can be understood as cloning another object that is the same as the original object. Note that it is another one.)
4. Method to automatically load objects. (Can be understood as a quote)

1. Object description and configuration

Method name: __tostring()
Format:

The code is as follows Copy code
class My {
 代码如下 复制代码
class My {
function __tostring() {
return "这里写这个类的文字描述"; //要用return,echo会出错。
}
}
$p = new My();
echo $p;
function __tostring() {

return "Write a text description of this class here"; //If you use return, echo will make an error.

}
 代码如下 复制代码
class My {
 function __toString() {
  return "这个类的作用是,保卫地球。";
 }
}
$p = new My();
echo $p;
?>
}

$p = new My(); echo $p;

Example:
The code is as follows Copy code
class My {
function __toString() {
return "The purpose of this class is to protect the earth."; }
 代码如下 复制代码
class My {
function __call($n,$v) {
echo "错误的方法名:".$n;
echo "错误的参数:".$v;
}
}
}

$p = new My();

echo $p;
 代码如下 复制代码

class My {
 function __toString() {
  return "这个类的作用是,保卫地球。";
 }

 function __call ($n,$v) {
  echo "错误的方法".$n."
";
    echo "错误的值".print_r($v).""; //值是以数组方式传递的,所以要用print_r。
 }
}
$p = new My();
$p->demo("第一",6);
?>

?>

2. Exception handling of object methods

Exception handling when calling some non-existent object methods allows the program to run normally.
Method name: __call($funname,$arr_value)
Format:

The code is as follows Copy code
class My { function __call($n,$v) {
 代码如下 复制代码
class My {
function __clone() {
echo "克隆时自动调用的函数";
}
}
$a = new My();
$b = clone $a;
echo "Wrong method name:".$n; echo "Wrong parameter:".$v; } }
Example:
The code is as follows Copy code
class My { function __toString() { return "The purpose of this class is to protect the earth."; } function __call ($n,$v) { echo "Wrong method".$n."
"; echo "Wrong value".print_r($v).""; //The value is passed in an array, so print_r is used. } } $p = new My(); $p->demo("First",6); ?>
3. Cloning of objects Clone can generate two identical objects in memory or upgrade the original object. (It is not a simple assignment, but two blocks of memory are opened in the memory. The cloned and the cloned are two different objects with the same attributes and methods) Method name: __clone() Keyword: clone Format:
The code is as follows Copy code
class My { function __clone() { echo "Function automatically called when cloning"; } } $a = new My(); $b = clone $a;


Example:

$p = new My(); $b = clone $p;
The code is as follows
 代码如下 复制代码

class My {
 public $name = "小猪";
 function __toString() {
  return "这个类的作用是,保卫地球。";
 }

 function __call ($n,$v) {
  echo "错误的方法".$n."
";
    echo "错误的值".print_r($v).""; //值是以数组方式传递的,所以要用print_r。
 }
}
$p = new My();
$b = clone $p;

echo $b->name="小猪头"."
"; //这是克隆并修改后的对象,如果使用 $b = $p,那修改$b->name="小猪头";后,再输出$p,也会被修改。
echo $p->name; //这是原对象,它已经被$b克隆了,其他都一样,但是他们是独立的。
?>

Copy code


class My { public $name = "Little Pig";

function __toString() {
return "The purpose of this class is to protect the earth.";
}

function __call ($n,$v) {
 代码如下 复制代码
function __autoload($class_n) {
include($class_n.".php");
}
$p = new MyPc(); //自动调用执行如下
$d = new demo(); //include("mypc.php")
echo "Wrong method".$n."
";

echo "Wrong value".print_r($v).""; //The value is passed in an array, so print_r is used.

}
 代码如下 复制代码

function __aotoload ($class_name) {
 include($class_name.".php"); //写在类外部。
}

$p = new class_name(); //这里实例化的类名就被上面的函数变量 $class_name 替代了,非常方便。
?>

}
echo $b->name="Little Pig Head"."
"; //This is the cloned and modified object. If $b = $p is used, then modify $b-> ;name="Little Pig Head";, and then output $p, it will also be modified.

echo $p->name; //This is the original object, which has been cloned by $b. Everything else is the same, but they are independent.

?> 4. Method of automatically loading objects Quickly get the object name and automatically load it into the current page Method name: __autoload()
Format:
The code is as follows Copy code
function __autoload($class_n) { include($class_n.".php"); } $p = new MyPc(); //The automatic call is executed as follows $d = new demo(); //include("mypc.php") Example:
The code is as follows Copy code
function __aotoload ($class_name) { include($class_name.".php"); //Written outside the class. } $p = new class_name(); //The class name instantiated here is replaced by the function variable $class_name above, which is very convenient. ?> http://www.bkjia.com/PHPjc/632640.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632640.htmlTechArticleThe magic functions in php include tostring, call, clone and autoload. I hope this tutorial will be useful to you. Friends can help. Summary of object-oriented development 1. Description and configuration of objects...
Statement
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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor