php magic method

Posted by vaavi8r on Fri, 11 Feb 2022 03:37:20 +0100

encapsulation

Use modifiers to modify member properties and member methods, hide the internal details of the object to the greatest extent, and ensure the integrity and security of the object

Object encloses variables and functions in curly braces

That is, object = {member attribute + member method} = {variable + function}

The emphasis is on integrity

Inside the object, member methods can directly access member properties Therefore, it is very convenient to transfer data between methods

Public public

Class member properties and methods can be read and called outside the class

If there is no modifier before the member method, it defaults to public

class Person 
{ 
	public $name;
    
	public function setName($str) 
	{ 
        // Assign values directly to member properties 
        $this->name = $str; 
	}
    
	public function getName() 
	{ 
        // Direct access to member properties 
        return $this->name; 
	} 
}

Private private

Class member properties and methods can only be read and called inside the class

Private member properties cannot be accessed directly outside the class

Private member methods cannot be called directly outside the class

// Lend money to friends 
class Person 
{ 
	private $card; // bank card 
	private $password; // password 
	private $money; // Cash on hand 
	
	// Withdraw money 
	private function qu_qian() 
	{ 
		$this-> money = bank->atm($this->card, $thid->password); 
	}
	
	// Lend others money 
	public function gei() 
	{ 
		$this->qu_qian(); // Money withdrawal is completed by the object itself and does not need to be known by others, so it is also private 
		return $this->money; 
	} 
}

Protected protected

Member properties and methods of class, Can only be read and called internally in this class and subclasses.

Protected member properties are outside the class    Not directly accessible     

Protected member methods are outside the class    Cannot be called directly

class Person 
{ 
    protected $name;
    protected $sex; 
    protected $age; 
    
    protected function getAge() 
    { 
    	return $this->age; 
    } 

    public function setAge($n) 
    { 
        if ($n>=0 && $n<120) { 
            $this->age = $n; 
        } else { 
            echo 'The setting age is not within a reasonable range!'; 
        }
    }
   
}

Magic Methods

__ When get gets the non-public or nonexistent member property in the object, trigger the method to accept a parameter property name

__ When set sets the non-public or nonexistent member attribute value in the object, the method is triggered to accept two parameters (attribute name and attribute value)

class Test 
{ 
	private $name = 'Jingshui'; 
	private $sex = 'male'; 
	private $age = 18; 
	
	// $prop is the name of the attribute to get 
	public function __get($prop) 
	{ 
		return $this->$prop; 
	}
	
	// $prop is the name of the attribute to be set and $value is the specific value to be set 
	public function __set($prop, $value) 
	{ 
		$this->$prop = $value; 
	} 
	
}
	
$obj = new Test; 
echo $obj->name; 	// Trigger__ get() 
$obj->sex = 'female'; 	// Trigger__ set() 
	
/* 
	These two methods replace multiple getXXX and setXXX methods 
	From the perspective of using classes, you don't need to know the getXXX and setXXX methods, 
	Just use the member attribute as public__ get and__ It will be natural,
	Transparent plays the purpose of protecting objects 
*/

__ When call() calls a non-public or nonexistent member method in the object, the method is triggered. The method accepts two parameters to trigger the scenario:

class Test
{

    // Private methods cannot be called directly from outside 
    private function add($a, $b) 
    {
    	return $a + $b; 
    }
    
    // $method is the name of the method to be called and $params is the parameter array when calling the method 
    public function __call($method, $params) 
    { 
    	return $this->$method(...$params); 
    }
}

$obj = new Test; 
echo $obj -> add(3, 4); 	// Trigger__ call() returns 7 

/* 
	There is a scenario that can be used__ call adds code before and after the execution of the original method
	For example: 
	public function __call($method, $params) 
	{ 
		// Pre code $this - > $method (... $params)// Post code 
	} 
*/

Other magic methods

__ When isset judges the non-public or non-existent attribute of the object, it triggers the method to accept a parameter attribute name

__ When unset destroys the non-public or nonexistent property of the object, the method is triggered to accept a parameter property name

class Test 
{ 
    private $name = 'Jingshui'; 
    private $sex = 'male'; 
    private $age = 18; 

    // Return the real result $prop attribute name to judge 
    public function __isset($prop) 
    { 
    	return isset($this->$prop); 
    }

    // Realize the destruction of private property $prop property to be destroyed 
    public function __unset($prop) 
    { 
    	unset($this->$prop);
    }
}

$obj = new Test; 

isset($obj->name); // Trigger__ isset() 
unset($obj->sex);  // Trigger__ unset()

__ clone this method is triggered when an object is cloned

class Test 
{ 
    private $name = 'wangjs'; 

    public function __clone() 
    { 
    	$this -> name = 'God'; 
    } 
}

$obj1 = new Test; 

$obj2 = clone $obj1; // Trigger__ clone

__ invoke triggers the method when the object is called as a function

class Test 
{ 
    public function __invoke() 
    { 
    	echo 'You think of me as a function call!'; 
    } 
}

$obj = new Test; 
$obj(); 	// Trigger__ invoke(), you can use parameters

__ toString this method is triggered when a string operation is directly performed on an object in a script

Function: string operation instead of object

<?php
	class A
	{
		public $name;

		public function say()
		{
			return 100;
		}

		public function __toString()
		{
            //You must return a value of string type in the method
			return '100';
		}
	}

	$a = new A;

	echo $a;
?>

inherit

Others have it, but I don't need to use inheritance to get all its things at this time

//Basic format
class A 
{ 
    public $name='Wang Jianshuang';
    
    public function say()
    {
    	echo 'Clear water makes no fish';
    } 
}

// Class B has all members of class A Class B is the subclass and class A is the parent
class B extends A  
{
    // There is nothing written here, and there are already member attributes and member methods in A
    
    // Add member properties and member methods
    public $sex = 'male'; 

    public function listen()
    {
    	echo 'Listen carefully,Stay up!<br>';
    } 
}

$b = new B; // Access members inherited from the parent class 

echo $b -> name,'<br>'; 
$b -> say(); // Access members unique to the parent class 

echo $b -> sex,'<br>'; 
$b -> listen();

/*
be careful:
	1)  B You can also add new member properties and methods
	2)  B You can also override existing member methods in
	
	When rewriting member methods, the number of parameters should be consistent, and the construction methods can be inconsistent
*/

private members in a parent class cannot be accessed in a child class

protected in the parent class modifies the member so that the member can also be accessed in the child class

       	 This category 	 Subclass 	Outside of class

public Y Y Y
private Y N N
protected Y Y N

Single inheritance

Only single inheritance is supported in php

// Parent - Human 
class Person 
{ 
    public $name; 
    public $sex; 
    public $age; 
    public function say(){} 
}

// Students inherit human beings 
class Student extends Person 
{ 
    public $num; 
    public function write(){} 
}

// Teachers inherit human beings 
class Teacher extends Person 
{ 
    public $money; 
    public function teach(){} 
}

/*
	Single inheritance is to inherit only one class at a time, and cannot inherit multiple classes continuously
*/

Overloading of subclasses

1. If the subclass overrides the method of the parent class, the instantiated object will call the subclass method when calling the method

2. If you want to call the method with the same name in the parent class in the method of the child class, you need to use the parent:: method name ()

3. When overriding member methods in subclasses, the number and type of parameters should be consistent, but the construction methods can be inconsistent

class A
{
    public $name; 
    
    public function __construct($name) 
    { 
    	$this->name = $name; 
    }
    public function add($a, $b) 
    { 
    	return $a + $b; 
    }
}

class B extends A 
{ 
    public $sex; 
    // When overriding construction methods, parameters can be inconsistent 
    public function __construct($sex, $name) 
    { 
    	parent::__construct($name); 
    	$this -> sex = $sex; 
    }
	
	// When overriding the parent class method, the parameters must be consistent (number, type) 
    public function add($x, $y) 
    {
        parent::add($x, $y);
    } 
}

$b = new B; 
echo $b -> add(3, 4);

final keyword

It is used to modify classes and member methods. Classes modified with final can instantiate objects but cannot be inherited. Modified methods can be called but cannot be overridden

// Indicates that this class cannot be inherited 
final class A 
{ 
    // Indicates that the method cannot be overridden 
    final public function say() 
    { 
    	echo 'Even if you break your throat, I'll keep writing!'; 
    } 
}

trait keyword

Similar to class, but structures defined with trait cannot instantiate objects

Declare the name of the trail to be combined by using the use keyword in the class

trait A
{
    public function say()
    {
        echo 'Method of speaking.....';
    }
}

trait B
{
    public function eat()
    {
        return 'How to eat.....';
    }
}

class C 
{
    // Use trait A and B as assembly parts of this class 
    use A,B;
    public function talk()
    {
        return 'Let's go out for a walk....';
    }
}

class D extends C
{ 
    public function run()
    {
        return 'It's already running.....';
    }
}

Topics: PHP Back-end