当前位置:网站首页>PHP - Common magic method (nanny level teaching)
PHP - Common magic method (nanny level teaching)
2022-07-06 07:52:00 【hcjtn】
PHP—— Common magic methods
php Specify two underscores (__) The first methods are reserved as magic methods
php It's an object-oriented language , however Previous php Language is really not , So there are some object-oriented standard implementations that are not perfect , For example, overloading . But we can make up for it by some magic methods .
In many cases , When we create the member attribute of an object , It can only be determined at a certain moment , This is not allowed before or after , But we can't give our member attribute a function value ( Attribute does not support ), So at this time, we need a specific method -—— Magic technique
for example :
<?php
class human{
// Member attribute
var $name;
var $sex
function human(){
echo '#########'; //echo() Function outputs one or more strings .
}
function wawaku(){
echo '555555555~';
}
}
$one=new huamn;
var_dump($one);
When I When the method name is the same as the class name , As soon as I create $one=new huamn;
This object , Will be output echo '#########'
This is when it was created , So after , I add the following sentence :
<?php
class human{
// Member attribute
var $name;
var $sex
// Member method
// Magic methods 1: Construction method
function human(){
echo '#########';
$this->sex = mt_rand(0,1) ? ' male ':' Woman ';
}
function wawaku(){
echo '555555555~';
}
}
$one=new human;
var_dump($one); //var_dump() Function is used to output information about variables .
When there are parameters in my construction method ,
function human($a)
So I $one There should also be a bracket after it , And fill in the corresponding parameters
$one=new human('a');
notes : This method is just an example , In real life, it is not recommended to use . Because once we change the class name , We have to put all human Change all to the same name , Otherwise, the construction fails
In real life , We use functions more often , for example __construct()
<?php
class human{
// Member attribute
var $name;
var $sex
// Member method
// Magic methods 1: Construction method
function __construct($name){
$this->sex = mt_rand(0,1) ? ' male ':' Woman ';
$this->name = $name;
}
function wawaku(){
echo '555555555~';
}
}
$one=new human('hcj');
var_dump($one);
therefore ,
Simply speaking , Magic method is a special function
Common magic functions
Construction method and analytical method
1.__construct()—— Construction method
__construct() It's a constructor
trigger : Instantiate in object ( Create objects ) It will trigger automatically when
effect : Initialize member properties
Parameters : There can be , There can be no , Depends on setting and logic
Return value : No,
Be careful : If the constructor has parameters , And the parameter has no default value , When instantiating an object , You must add arguments in parentheses after the class name
<?php class human{ // Member attribute var $name; var $sex; var $id; // Member method // Magic methods 1: Construction method function __construct($name){ $this->sex = mt_rand(0,1) ? ' male ':' Woman '; $this->name = $name; $this->id = uniqid(); //uniqid() Generate a unique ID } function wawaku(){ echo '555555555~'; } } $one=new human('hcj'); var_dump($one);
2. __desctruct()—— destructor
__desctruct() Destructor , Calls that don't need to be displayed , The system will call this method automatically . And destructors don't need parameters ( Because there is no need to call )
trigger : Automatically triggered when the object is destroyed (unset() perhaps Page execution complete )
effect : Recycle resources during the use of objects , coordination unset Use
Parameters : No,
Return value : No,
<?php class human { var $name; var $sex; var $id; function __construct($name){ $this->sex = mt_rand(0,1) ? ' male ':' Woman '; $this->name = $name; $this->id = uniqid(); //uniqid() Generate a unique ID } function __destruct($name){ echo '@@@@@@@@@@'; unset($this->id); } } $one=new human('hcj'); var_dump($one); unset($one); // notes : Here we cannot detect , Because at this time ,one Has been logged off , Can't view id situation
** Three characteristics of object-oriented :
- encapsulation
- Inherit
- polymorphic ( An idea )
Object oriented encapsulation features
Package characteristics : After an object is generated , Some member properties and member methods of an object are logically not allowed to be called or used outside the object . This is the origin of packaging features
Encapsulated keywords :private Private
private Characteristics of :
- By private Decorated member properties cannot be accessed outside the class , Can be accessed inside the class .
- By private Decorated member methods cannot be accessed outside the class , Can be accessed inside the class .
- var and private Only one... Can be selected ( Include public and protected )
<?php var xiyiji { private $color = ' white '; var $pinpai = ' haier '; var $weight = '20kg'; var $rongliang = '6.5L'; private $mada = ' Mitsubishi Heavy Industries '; // Member method // How to wash clothes private function xiyi() { echo ' Wash the clothes '; $this->settime(); } private function tuoshui() { echo' dehydration '; } private function settime() { echo' Timing function '; echo $this->mada.' Turn on the timing function '; } } // Instantiate a laundry object $one= new xiyiji(); var_dump($one); echo $one->xiyi(); // Find that you can call , Mitsubishi Heavy Industries starts the timing function for washing clothes // Try to modify private Decorated member attribute value '''$one->made = ' Learning garden '; var_dump($one);''' // Find out about , Change failed , So we need magic to open a back door // Magic methods __get()
Magic methods : __get( Access back door )
- trigger : Automatically triggered when accessing private member properties
- function :1. Prevent error reporting 2. Provide a back door for private member property access
- Parameters : One Access private member attribute name
- Return value : There can be , There can be no , The actual situation determines
- Be careful :__get Functions can only be viewed and cannot be modified .
<?php
var xiyiji {
// Member attribute
private $color = ' white ';
var $pinpai = ' haier ';
var $weight = '20kg';
var $rongliang = '6.5L';
private $mada = ' Mitsubishi Heavy Industries ';
// Member method
// How to wash clothes
private function xiyi() {
echo ' Wash the clothes ';
$this->settime();
}
private function tuoshui() {
echo' dehydration ';
}
private function settime() {
echo' Timing function ';
echo $this->mada.' Turn on the timing function ';
}
function __get($pro) {
//__get When I call private member properties , This method will be called , But not all private member attributes I need to see , So there should be a judgment
if($pro == 'name'){
echo '######';
// echo $this->color;
return $this->$pro;
}else{
return ' Prohibit viewing ';
}
}
}
// Instantiate a laundry object
$one= new xiyiji();
var_dump($one);
echo $xiyiji->color;
echo '<hr/>';
echo $xiyi->settime;
//xiyiji->color='red'; Found that the failure
- Magic methods : __set()
- Departure time : Automatically triggered when setting the value of the private member property
- function :1. Shielding error 2. Provide a back door for private member property settings
- Parameters : Two $a The original value of the private member property $b New value of private member property
- Return value : no return value
<?php
class Person {
// Member attribute
var $name = ' Li Lanying ';
private $sex = ' male ';
var $age = '38';
// Member method
function say(){
echo ' Buddha is auspicious ';
}
function nn(){
echo ' Hua Lala ~';
}
// Magic methods __set($a,$b){ $a The original value of the private member property $b New value of private member property
function __set($a,$b){
if($pro == 'sex'){
echo '##';
//var_dump($a);
//var_dump($b);
$this->$a = $b
}else{
echo ' No modification ';
// no return value
}
}
}
}
// Instantiate objects
$lly = new Person;
var_dump($lly);
// Access private member properties
// echo $lly->sex;
// Set private member properties
$lly->sex = ' Simon? ';
var_dump($lly);
- Magic methods :__isset
- trigger : Modify the private member attribute isset Automatically trigger when checking
- function : Instead of outside the object isset Function detection , Return results
- Parameters :1 individual , Private member attribute name
- Return value : Generally return to isset() Examination result
<?php
class Person {
// Member attribute
var $name = ' Li Lanying ';
private $sex = ' male ';
var $age = '38';
// Member method
function say(){
echo ' Buddha is auspicious ';
}
function nn(){
echo ' Hua Lala ~';
}
// Magic methods __set($a,$b){ $a The original value of the private member property $b New value of private member property
function __set($a,$b){
if($pro == 'sex'){
echo '##';
//var_dump($a);
//var_dump($b);
$this->$a = $b
}else{
echo ' No modification ';
// no return value
}
}
function __isset(){
echo '######';
var_dump($pro);
// return isset($this->$pro);
}
}
// Instantiate objects
$lly = new Person;
// Check whether the name attribute is set Non private
//$result = isset($lly->name);
//var_dump($result); ture
// External isset Cannot detect private member properties The return value is false
''' Check private properties '''
$result = isset($lly->sex);
var_dump($result)
Magic methods :__unset
- trigger : Modify the private member attribute unset Automatically trigger when checking
- function : Instead of outside the object unset Function detection ,
- Parameters :1 individual , Private member attribute name
- Return value : nothing
<?php
class Person {
// Member attribute
var $name = ' Li Lanying ';
private $sex = ' male ';
var $age = '38';
// Member method
function say(){
echo ' Buddha is auspicious ';
}
function nn(){
echo ' Hua Lala ~';
}
function __unset(){
//var_dump($a);
if($pro == 'sex'){
unset($this->$pro);
}
}
}
// Instantiate objects
$lly = new Person;
// Delete an attribute Non private
''' unset($lly->name); var_dump($lly);'''
// Delete a private member attribute
unset($lly->sex);;
var_dump($lly)
Object oriented inheritance features
Inheritance features :
Inheritance format :
class Class name extends Father's name {
The unique method of writing subclass and human writing ;
}
Concept :
- father : Interpreted parent class inherited by other classes , Also called base class ;
- Subclass : A class that inherits from other classes is a subclass , Also called derived classes .
characteristic :
The subclass inherits the parent class, which has both the All member properties and methods ( private private Except for )
After inheriting the parent class, a subclass can have properties and methods unique to the subclass .
Grandpa has Father, too Father has Grandpa may not have
On inheritance , Subclasses allow methods with the same name as the father , This situation will not conflict , Instead, the methods of the subclass will override the methods of the parent class , This method is called overloading ( Reload ).
Magic methods can be inherited by subclasses .
If the parent class has a constructor , Subclasses also need construction methods , At this time, you need to overload the constructor of the father in the subclass , And in the construction method
parent::__construct ()
Call the father's constructor , Construct inherited father's member properties . You can also useClass name ::__construct ()
To invoke the constructor of the parent class , It is not recommended to use . Once the name of the parent class changes , Inheritance fails .Don't inherit blindly when inheriting code , Humans should not inherit birds . There must be a certain logical relationship .
php The difference between inheritance characteristics and inheritance of other languages :
- php Time order inheritance ( Biological logic ) Language Other languages usually inherit ( Sociological logic , One apprentice has many masters ).
<?php
// Inheritance features Grandpa has Father, too Father has Grandpa may not have
// Grandpa
class GrandFather{
// Member attribute
var $familyname = ' Cao ';
var $lastName = ' fuck ';
private $xifu = ' The wife ';
// Member method
// having dinner
function chi {
echo ' Will eat ';
}
function he {
echo ' Can drink water ';
}
function __construct{
$this->lastName= ' Tianjiao ';
}
}
''' // Fathers class Father{ // Member attribute var $familyname = ' Cao '; var $lastName = ' fuck '; var $money = '100'; // Member method // having dinner function chi { echo ' Will eat '; } function he { echo ' Can drink water '; } function piao { echo ' Foot bath members '; } } $father = new Father; var_dump (Father); // But generally, we don't use the way of copying code to inherit '''
// Fathers
class Father extends GrandFather{
var $money = '100';
function piao() {
echo ' Foot bath members ';
}
}
function __construct{
$this->sex = mt_rand(0,1) ? ' male ':' Woman ';
//$this->lastName= ' Tianjiao ';
// Call the father's constructor
//GrandFather::__construct
// Call the father's constructor 2
}
$father = new Father;
var_dump (Father);
Access type control
- Three encapsulated keywords
- private Private encapsulation
- public Public encapsulation
- protected Protected packaging ( Only when inherited will it be protected )
- The encapsulation level of methods with the same name of subclasses must Greater than or equal to the parent class Packaging level
- private -1 protected-2 public-3
- var Is to encapsulate keywords , But it is not a standard encapsulated keyword , Generally, it is only used for testing and learning .
- var=%50 public
- reason :var Only member attributes can be decorated , Member methods cannot be decorated .
- var=%50 public
keyword / Location | Out of class | Intra class | Subclass |
---|---|---|---|
private | x | √ | x |
public | √ | √ | √ |
protected | x | √ | √ |
<?php
class libei {
// Member attribute
protected $fname =' Liu ';
private $lastname = ' To prepare ';
public $horse = ' Dilu ';
// Method
private function cry(){
echo ' Sobbing, sobbing, sobbing ~';
}
protected function say(){
echo ' Talking ';
}
public function zhandou(){
echo ' In battle ';
}
''' function texvisit(){ echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname; The inside of the class can access }'''
}
// Instantiate a Liu Bei object
$lb = new luibei();
// Access member properties outside the class
'''echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname; Only Lu (public) To access The rest cannot be accessed '''
'''class adou extends luibei{ function texvisit(){ echo $lb->horse; echo '<br/>'; echo $lb->lastname; echo '<br/>'; echo $lb->fname; }; // Instantiate a Dou object $ad = new adou; $ad->texvisit(); Lu can Liu can '''
边栏推荐
- 链表面试题(图文详解)
- flask返回文件下载
- File upload of DVWA range
- Redis list detailed explanation of character types yyds dry goods inventory
- onie支持pice硬盘
- 解决方案:智慧工地智能巡檢方案視頻監控系統
- Related operations of Excel
- TS 类型体操 之 循环中的键值判断,as 关键字使用
- Key value judgment in the cycle of TS type gymnastics, as keyword use
- 成为优秀的TS体操高手 之 TS 类型体操前置知识储备
猜你喜欢
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
智能终端设备加密防护的意义和措施
数据治理:主数据的3特征、4超越和3二八原则
861. Score after flipping the matrix
数字经济时代,如何保障安全?
QT color is converted to string and uint
Force buckle day31
Secure captcha (unsafe verification code) of DVWA range
合规、高效,加快药企数字化转型,全新打造药企文档资源中心
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
随机推荐
Brief explanation of instagram operation tips in 2022
Mise en œuvre du langage leecode - C - 15. Somme des trois chiffres - - - - - idées à améliorer
datax自检报错 /datax/plugin/reader/._drdsreader/plugin.json]不存在
Transformer principle and code elaboration
Epoll and IO multiplexing of redis
Games101 Lesson 7 shading 1 Notes
数据治理:数据质量篇
Document 2 Feb 12 16:54
21. Delete data
Opencv learning notes 9 -- background modeling + optical flow estimation
[非线性控制理论]9_非线性控制理论串讲
烧录场景下的源代码防泄密方案分享
[CF Gym101196-I] Waif Until Dark 网络最大流
Qualitative risk analysis of Oracle project management system
edge浏览器 路径获得
Common functions for PHP to process strings
Oracle time display adjustment
octomap averageNodeColor函数说明
On why we should program for all
edge瀏覽器 路徑獲得