Advanced application of PHP objects

Keywords: PHP Back-end

1. Advanced application of PHP objects

final keyword
Final means "final" and "final"; The classes and methods modified by final are the "final version";
If there is a method, the format is:

final class class name{
//...
}

Indicates that this class is no longer inherited and cannot have subclasses;
If there is a method, the format is:

final function method name()

It indicates that the method cannot be overridden or overridden in subclasses;
Example: set the keyword final for the Employee class and generate a subclass MyEmployee,

<?php
//Create a final decorated Employee class
final class Employee{
    //Construction method
    function __construct(){
        echo "Employee class";
    }
}
//Create a subclass of Employee
class MyEmployee extends Employee{
    static function work(){
        echo 'MyEmployee Subclass';
    }
}
MyEmployee::work();
?>

2. Abstract class

Abstract class is a class that cannot be instantiated and can only be used as other parent classes;
Abstract classes are declared with the abstract keyword in the following format:

abstract class AbstractName{
//....
}

Abstract classes are similar to ordinary classes, including member variables and member methods; The difference is that an abstract class must contain and rewrite at least some specific methods;
Example: implement the Animal abstract class Animal, which contains the abstract method eat();

<?php
//Create abstract class Animal
abstract class Animal{
    //Define abstract methods
    abstract function eat();
}
//Define Dog class and inherit abstract class Animal
class Dog extends Animal{
    //Implementing parent class methods
    function eat()
    {
        echo "Dogs like to eat bones!";
    }
}
//Define Cat class and inherit abstract class Animal
class Cat extends Animal{
    function eat()
    {
        echo "Cats like to eat fish!";
    }
}
//instantiation 
$dog = new Dog();
$cat = new Cat();
//Call method
$dog -> eat();
echo "<br>";
$cat ->eat();
?>

The execution results are as follows:

3. Use of interface

Inheritance simplifies the creation of objects and classes and increases the reusability of code;
PHP only supports single inheritance. If you want to realize multiple inheritance, you should use the interface; PHP can implement multiple interfaces;
The interface is declared through the interface keyword, and the interface contains unimplemented methods and some member variables. The format is as follows:

interface InterfaceName{
function interfaceName1();
function interfaceName2();
...
}

Do not use keywords other than public to modify class members in the interface. For methods, do not write keywords; Determined by the attributes of the interface itself;
Subclasses implement interfaces through the implements keyword. To implement multiple interfaces, each interface should be separated by commas;
All unimplemented methods in the interface need to be implemented in subclasses, otherwise PHP users will have errors;
The format is as follows:

<?php
class itfClass implements InterfaceName1,InterfaceName2{
    function InterfaceName1(){
        ...
    }
    function InterfaceName2(){
        ...
    }
}
...
?>

Example: declare two interfaces, Dogs and Animal, and then declare two subclasses, dog and huskie, where dog class inherits Dogs interface and huskie class inherits Dogs and Animal interfaces; After implementing their member variable methods respectively, instantiate two objects $dog and $huskie; Then call the implemented method;

<?php
//Declare interface Anim
interface Animal{
    function eat();
}
//Declare interface Dog
interface Dogs{
    function play();
}

//Defines the Dog and implements the Dogs interface
class Dog implements Dogs{
    function play()
    {
        echo "A dog plays with humans!";
    }
}
//Define the subclass Huskie to implement the Dogs interface and the Animal interface
class Huskie implements Dogs,Animal{
    function play()
    {
        echo "A husky dog doesn't play with humans!";
    }
    function eat()
    {
        echo "Husky eats everything!";
    }
}
//instantiation 
$dog = new Dog();
$huskic = new Huskie();
//Call the play() method of the Dog class
$dog -> play();
echo "<br>";
//Call the play() and eat() methods of Huskie class
$huskic ->play();
$huskic ->eat();
?>

The execution results are as follows:

The functions implemented by abstract classes and interfaces are very similar; The advantage of abstract class is that it implements public methods in abstract classes, and interfaces can realize multiple inheritance;

4. Clone objects

1. Clone objects

Object is used as a common data type; If you want to reference an object, use "&" to declare it, otherwise PHP will pass the object by value in the default way;
Example: instantiate the object of the Employee class and pass it to the object e m p 1 , emp1, Emp1, the default value of emp1 is Wang, and then set the object e m p 1 , send use universal through number according to class type of Fu value square type Fu value to yes as emp1, assign the value to the object using the assignment method of common data type emp1, assign the value to the object emp2 using the assignment method of common data type, and change e m p 2 of value by thank some , again transport Out yes as The value of emp2 is Xie, and then the object is output The value of emp2 is Xie, and then the value of object emp1 is output;

php
<?php
//Class Employee
class Employee{
    //private variable
    private $name='Wang Mou';
    //Declare get/set method
    public function setName($name){
        $this ->name = $name;
    }
    public function getName(){
        return $this ->name;
    }
}

//instantiation 
$emp1 = new Employee();
//Assign the value to the object $emp2 using the normal data type
$emp2 = $emp1;
//Change the value of $emp2
echo "object\$emp1 The value of is:".$emp1 -> getName();
?>

The execution results are as follows

2. _clone() method

In addition to simple cloning, sometimes cloned objects have their own properties and methods, which can be implemented by _clone();
The function of __clone() is to invoke the __clone() method in the process of cloning objects, so that cloned objects can maintain some of their own methods and attributes.
Example: create _clone() method in class Employee. The function of this method is to change the default value of variable $name from Wang to Xie; clone object $emp2 from object $emp1 and output the value of $name of $emp1 and $emp2;

<?php
//Class Employee
class Employee{
    //private variable
    private $name='Wang Mou';
    //Declare get/set method
    public function setName($name){
        $this -> name = $name;
    }
    public function getName(){
        return $this -> name;
    }
    //Declare _clone() method
    public function __clone(){
        //Change the value of the variable $name to Xie
        $this -> name ='Xie Mou';
    }
}

//instantiation 
$emp1 = new Employee();
//Assign a value to the object $emp2 using the cloned method
$emp2 = clone $emp1;
//Output value of $emp1
echo "object\$emp1 The value of is:".$emp1 -> getName();
echo "<br>";
//Output $emp2 value
echo "object\$emp2 The value of is:".$emp2 -> getName();
?>

The execution results are as follows:

5. Comparison object

In the development process, to judge whether the relationship between two objects is clone or reference, use the comparison operators "= =" and "= ="; two equal signs are the content of the comparison object, and three equal signs are the reference address of the comparison object;
Example: instantiate the object $emp, create clone objects and references respectively, and use "= =" and "= =" to judge the relationship between them;

<?php
//Create Employee class
class Employee{
    private $name;
    function __construct($name){
        $this -> name = $name;
    }
}
//Instantiate object
$emp = new Employee('Wang Mou');
//Clone object $coneemp
$cloneemp = clone $emp;
//Reference object $emp1
$emp1 = $emp;
//==Compare the cloned object with the original object
if($cloneemp==$emp){
    echo "The contents of the two objects are the same<br>";
}
//====Compare the reference object with the original object
if($emp1===$emp){
    echo 'The reference addresses of the two objects are the same';
}
?>

The execution results are as follows:

6. Type of test object

The instanceof operator can detect which class the current object belongs to;
The format is:

ObjectName instanceofClassName

Example: create two - base class Employee and subclass Animal; instantiate a subclass object, judge whether the object belongs to this subclass, and then judge whether the object belongs to this base class;

<?php
//Create Employee
class Employee{}
    //Create an Animal class
    class Animal extends Employee{
        private $type;
    }
    //Instantiate object
    $animal = new Animal();
    //Judge whether it belongs to Animal class
    if($animal instanceof Animal){
        echo "object\$animal belong to Animal class"."<br>";
    }
    //Judge whether it belongs to Employee class
    if($animal instanceof Employee){
        echo "object\$animal belong to Employee class"."<br>";
    }
?>

The execution results are as follows:

7. Magic method (_)

All methods starting with "_" are reserved in PHP. You can only use the existing methods in PHP and cannot create them yourself;

1. _set() and _get() methods

The functions of the two magic methods are:

  1. When the program attempts to write a non-existent or invisible member variable, PHP will execute the _set() method; the _set() method contains two parameters, representing the variable name and variable value respectively; the parameters cannot be omitted;
  2. When the program calls an undefined member variable, the variable value can be read through the _get() method. The _get() method has a parameter indicating the variable name to be called;

Magic methods must be defined in the class before they can be used. PHP will not execute undefined magic methods;
Example: declare class Employee and create a private variable KAtex parse error: expected group after '' At position 14: type and two magic methods -_ ̲_ set() and__ get();… emp, first assign and call the existing private variable, and then call the undeclared variable $name ';

<?php
//Class Employee
class Employee{
    //private variable
    public $type='';
    //__ get() magic method
    private function __get($name)
    {
        //Judge whether it is declared
        if(isset($this -> $name)){
            echo "\$name The value is:".$this -> $name."<br>";
        }else{
            //Not declared, initialize
            echo "variable\$name Undefined, initial value is 0<br>";
            $this -> $name = 0;
        }
    }
}

$emp = new Employee();
$emp->type="Emp";
//Call variable
$emp->type;
$emp->name;

//Create Employee class
class Employee{
    public function work(){
        echo "work Method exists!<br>";
    }
    //call method
    public function __call($method,$parameter){
        echo "Method does not exist, execute__call()<br>";
        echo "Method name:".$method."<br>";
        echo "The parameters are:";    //The parameter is an array of parameters
        var_dump($parameter);
    }
}
//Instantiate object
$emp = new Employee();
//Call an existing method
$emp->work();
//Calling a method that does not exist
$emp->wor('Wang Mou',22,'Nanjing');
?>

2. __call() method

__ The call() method is used: when a program attempts to call a member method that cannot exist or is invisible, PHP will call the method first to store the method name and its parameters;
__ The call() method contains two parameters, method name and method parameter;
Method parameters exist in the form of an array;
Example: declare the class Employee, which contains two methods - work() and play(). To instantiate the object $emp, you need to call two methods: one is the work() method existing in the class, and the other is the non-existent wor() method;

<?php
//Define class Employee
class Employee{
    public function work(){
        echo "work()Method exists!<br>";
    }
    //call method
    public function __call($method, $prameter)
    {
       echo "Method name does not exist, execute__call()<br>";
       echo "Method name:".$method."<br>";
       echo "The parameters are:";     //The parameter is an array of parameters
        var_dump($prameter);
    }
}
//Instantiate object
$emp = new Employee();
//Call an existing method
$emp->work();
//Calling a method that does not exist
$emp-wor('king',33,'Nanjing');
?>

The execution results are as follows:

3. __sleep() and__ wakeup() method

PHP can instantiate an object by using the serialize() function, that is, all the variables in the object are saved, and only the class name is saved for the class in the object;
When using the serialize() function, if the instantiated object contains__ sleep() method, execute first__ sleep() method;
This method can clear the object and return an array containing all variables in the object;
Use__ The sleep() method is used to close the database connection and other aftercare operations that the object may have;
The unserialize() function can restore the objects serialized by the serialize() function__ The wakeup() method recovers the data connection and related work that may be lost in serialization;
Example: declare the class Employee, which has two methods -__ sleep() and__ wakeup(); Instantiate the object $emp, use the serialize() function to serialize the object into a substring $i, and finally use the serialize() function to restore the substring $i to a new object;

<?php
//Define class Employee
class Employee{
    //Declare private variables
    private $name="Wang Mou";
    //Declare get method
    public function getName(){
        return $this->name;
    }
    //Declare magic method__ sleep()
    public function __sleep(){
        echo "use serialize()Function to save the object, which can be stored locally or in the database";
        return array('name');
    }
    //Declare magic method__ wakeup()
    public function __wakeup(){
        echo "When using this data, use unserialize()Function operates on the serialized string and converts it back to an object";
    }
}
//Instantiate object
$div = new Employee();
//serialized objects 
$i=serialize($div);
//Output string i
echo 'String after serialization'.$i."<br>";
//Reconverting objects
$emp1 = unserialize($i);
//Using the getName method
echo 'The restored member variables are:'.$emp1->getName();
?>

The execution results are as follows:

4. __toString() method

Magic method__ toString() is used to convert an object into a string when using echo or print to output an object;
Example: output the object $emp of class Employee, and the output content is__ Contents returned by toString() method;

<?php
//Define class Employee
class Employee{
    //Declare private variables
    private $type="Emp";
    //Statement__ toSring() method
    public function __toString(){
        return $this->type;
    }
}
//Instantiate object
$emp = new Employee();
//Output object
echo "object\$emp The value of is:".$emp;
?>

The execution results are as follows:

Note: if not__ toString() method, a fatal error will occur when the object is output directly;
When outputting objects, it should be noted that echo or print is directly followed by the object to be output, and the opposite character should not be added in the middle, otherwise__ The toString() method will not be executed;

5. __autoload() method

__ The autoload() method can automatically instantiate the class to be used;
Example: create the class file Employee.class.php; The file contains the class Employee. Create the index.php file in the file__ autoload() method to manually realize the search function. If the search is successful, use include_ The once() function dynamically introduces the file;
Employee.class.php class file

<?php
//Define class Employee
class Employee{
    //Declare private variables
    private $name;
    //Create construction method
    public function __construct($name){
        $this->name=$name;
    }
    //Create__ toString() method
    public function __toString(){
        return $this->name;
    }
}
?>

index.php file

<?php
//Create__ autoload() method
function __autoload($class_name){
    //Class file address
    $class_path = $class_name.'Employee.class.php';
    //Determine whether the class file exists
    if(file_exists($class_path)){
        //Dynamic import class file
        include_once($class_path);
    }else{
        echo "Classpath error";
    }
}
//Instantiate object
$emp = new Employee("Xie Mou");
//Output the contents of the class
echo $emp;

?>

The execution result is not the expected result:

8. Object oriented application -- interception class of Chinese string

Example: write the MysubStr class and define the mysubstr() method to intercept the Chinese string and avoid the problem of garbled code when intercepting the Chinese string;

<?php
class MsubStr{
    //$str specifies the string, $start specifies the starting position of the string, and $len specifies the length
    function csubstr($str,$start,$len){
        //$strlen specifies the total length of the string
        $strlen=$str+$len;
        //for loop reads string
        for($i=0;$i<$strlen;$i++){
            //If the ASCII value of the first byte in the string is greater than 0xa0, it indicates Chinese characters
            if(ord(substr($str,$i,1))>0xa0){
                //Take two characters and assign them to the variable $sstr, which is equal to one Chinese character
                $tmpstr=substr($str,$i,2);
                //Variable plus 1
                $i++;
            }else{
                //Not a string. Take out one character at a time and assign it to a variable
                $tmpstr=substr($str,$i,1);
            }
        }
        //Return string
        return $tmpstr;
    }
}
//Instantiation class
$mc = new MsubStr();
?>
<table>
<tr>
    <td>
        <?php
            $strs="PHP Is a general, open source scripting language";
            //Judge string length
            if(strlen($str)>10){
                //Use the substr() function to intercept 9 characters in the string
                echo substr($str,0,9)."...";
            }else{
                echo $str;
            }
        ?>
    </td>
</tr>
<tr>
    <td>
        <?php
            $strs="Grammar absorbed C,java and Perl Characteristics of language";
            //Judge string length
            if(strlen($strs)>10){
                //Use the substr() function to intercept 9 characters in the string
                echo substr($strs,0,9)."...";
            }else{
                echo $strs;
            }
        ?>
    </td>
</tr>
</table>

The execution results are as follows:

Conclusion

If this article helps you, give a praise and collect a collection. You are welcome to leave a message and comment;
If there are any mistakes in the article, you are welcome to give advice.

Posted by HuggieBear on Sat, 04 Dec 2021 11:10:40 -0800