A, polymorphism

Polymorphism: Morphologic polymorphism comes in two types: method overrides and method overrides

1.1 Method Override

A subclass overrides a method of the same name from its parent class


      
    / / parent class
    class Person {
        public function show () {
            echo 'This is the superclass 

'
; }}/ / subclass class Student extends Person { // The subclass overrides the superclass's method of the same name public function show () { echo 'This is a subclass

'
; }}/ / test $stu = new Student; $stu->show(); ? > Copy the code

Effect:Notes:

  1. The methods of the subclass must have the same name as the methods of the superclass
  2. The number of parameters must be the same
  3. A child class cannot be modified more strictly than a parent class

1.2 Method overloading

Method overloading: In the same class, there are multiple functions with the same name, by the different arguments to distinguish between different methods, called method overloading.Note: PHP does not support method overloading, but PHP can simulate method overloading in other ways.

1.3 Private property inheritance and rewriting

Private properties can be inherited but cannot be overridden. Such as:


      
 
    class A {
        private $name = 'Javascript';
    }
    class B extends A {
        private $name = 'Java';
    }
    $obj = new B();
    var_dump($obj);
? >
Copy the code

Effect:You can see that private properties can be inherited, but not overridden.


Examples:


      
 
    class A {
        private $name = 'Javascript';
        public function showA () {
            echo $this->name,'<br/>'; }}class B extends A {
        private $name = 'Java';
        public function showB () {
            echo $this->name,'<br/>'; }}$obj = new B();
    $obj->showA();
    $obj->showB();
? >
Copy the code

Effect:Analysis:

ShowA () and showB() both represent objects of B, which inherit the private property of A, so there are two of these in B, which inherit the private property of A, So there are two this in B. In showA(), only the name in A can be accessed, but not the name in B. The name in B cannot be accessed. In showB(), only the name in B can be accessed, but not the name in A

Method modifiers

Method modifiers are static, final, and abstract

2.1 Static

  1. Static properties are called static properties and static methods are called static methods
  2. Static members allocate space when a class is loaded and are destroyed when the program is finished
  3. Static members are only one in memory
  4. Call syntaxClass name :: attribute Class name: method name ()

Ex. :


      
 
    class Person {
        public static $add='xiamen';
        public static function show() { // There is no order in modifiers. You can write static before public
            echo 'I'm a static method 

'
; }}echo Person::$add.'<br/>'; Person::show(); ? > Copy the code

Effect:


1, count the number of people (add one by one) (error code)


      
 
    class Student {
        private $num = 0;
        public function __construct() {
            $this->num++;
        }
        public function show() {
            echo "The total number is:{$this->num}"; }}$stu1 = new Student;
    $stu2 = new Student;
    $stu2->show();
    
? >
Copy the code

Effect:Analysis: because private is ordinary private variables, instantiation, assignment once again. So you can’t write it like that.

To write correctly:


      
 
    class Student {
        private static $num = 0;
        public function __construct() {
            self: :$num+ +; }public function show() {
            echo 'The total number of people is:'.self: :$num.'<br/>'; }}$stu1 = new Student;
    $stu2 = new Student;
    $stu2->show();
    
? >
Copy the code

Effect:Self always represents the class name of the current class.


Static members can also be inherited:


      
    class Person {
        public static $add='Amoy';
        public static function show() {
            echo 'I'm a static method'; }}/ / inheritance
    class Student extends Person {}/ / test
    echo Student::$add.'<br/>';
    Student::show();
? >
Copy the code

Effect:


Static delay binding Static indicates the class to which the current object belongs. Ex. :


      
    class Person {
        public static $type='human beings';
        public function show1 () {
            echo static: :$type.'<br/>'; }}class Student extends Person {
        public static $type='students';
        public function show2 () {
            echo static: :$type; }}$obj = new Student();
    $obj->show1();
    $obj->show2();
? >
Copy the code

Effect:Self, even if the code doesn’t run, you can see that it always represents the current class, whereas static doesn’t know what class it represents until it runs, so it’s called static delayed binding.

Summary:

1. Static has only one copy in memory and allocates space 2 when the class is loaded. If there are more than one modifier, there is no order among the modifiers. Self is the name of the class in which the object belongs. Static is the class in which the object belongs

(2) This is the final result.

Final-modified methods cannot be overridden. Final-modified classes cannot be inherited

Ex. :


      
    class Person {
        public static $type='human beings';
        final public function show () {
            echo static: :$type.'<br/>'; }}class Student extends Person {
        public static $type='students';
        public function show () {
            echo static: :$type; }}? >
Copy the code

Effect:If a class is determined not to be inherited and a method is determined not to be overridden, the final modifier can be used to improve execution efficiency. If a method is not allowed to be overridden by another class, we can use the final modifier.

2.3 abstract

  1. Abstract methods are abstract methods, and classes are abstract classes
  2. A declaration with only methods and an implementation without methods is called an abstract method
  3. If a method in a class is abstract, the class must be abstract
  4. The characteristic of abstract classes is that they cannot be instantiated
  5. If a subclass inherits from an abstract class, it must re-implement all the abstract methods of its parent class, or it will not be allowed to instantiate
  6. A class that has no abstract method can be declared as an abstract class to prevent the class from instantiating

Ex. :


      
    / / abstract classes
    abstract class Person {
        public abstract function setInfo(); // Abstract method
        public function getInfo () {
            echo 'Get information 

'
; }}//$obj = new Person(); // Not allowed to instantiate / / inheritance class Student extends Person { public function setInfo () { echo 'Reimplement the superclass abstract method

'
; }}$obj = new Student; $obj->setInfo(); $obj->getInfo(); ? > Copy the code

Effect:Abstract classes do:

  1. Used to define naming conventions
  2. Prevent instantiation. If all the methods in a class are static methods, there is no need to deinstantiate. You can use abstract methods to prevent instantiation

Class constants

Class constants are const examples:


      
    class Student {
       public const ADD='Address unknown'; // Access modifiers are not supported until after 7.1
    }

    echo Student::ADD;
? >
Copy the code

Effect:Question 1: What is the difference between define and const constants? A: Const constants can be members of a class. Define constants cannot be members of a class. Question 2: What is the difference between constant and static properties? A: Similarities: space is allocated when the class is loaded. Differences: The values of constants cannot be changed. The values of static properties can be changed

Four, interfaces,

4.1 interface

  1. If all the methods in a class are abstract methods, then the abstract class can be declared as an interface
  2. An interface is a special abstract class. There are only abstract methods and constants in the interface
  3. An abstract method in an interface must be public and can be omitted. The default is public
  4. Implements the interface with the implements keyword
  5. You cannot use abstract and final to decorate abstract methods in an interface

Ex. :


      
    // Declare the interface
    interface Person {
        const ADD='China';
        function fun1 ();
        function fun2 ();
    }
     
    // Interface implementation
    class Student implements Person {
        public function fun1() {}public function fun2() {}}// Access constants in the interface
    echo Person::ADD;
? >
Copy the code

Effect:

4.2 Multiple implementations of interfaces

Classes do not allow multiple inheritance, but interfaces allow multiple implementations. Ex. :


      
    // Declare the interface
    interface IPic1 {
        function func1 ();
    }
     
    interface IPic2 {
        function func2 ();
    }

    // The interface allows multiple implementations
    class Student implements IPic1.IPic2 {
        public function func1 () {}public function func2 () {}}? >
Copy the code

Note: 1. In multiple implementations of an interface, if there is a method with the same name, only implement it once. 2. Classes can inherit while implementing interfaces.

Ex. :

class Student extends Person implements IPic1.IPic2 {}Copy the code

Anonymous classes

PHP7.0 + support example:


      
    $stu = new class {
        public $name = 'tom';
        public function __construct () {
            echo Constructor 

'
; }};echo $stu->name; ? > Copy the code

Effect:Summary: Anonymous classes can be used if the class is instantiated only once. Benefit: After instantiation, the space of the class is reclaimed.

Vi. Method binding

PHP7.0 + support: bind methods to objects. Grammar:

Closure -> Call (object): Bind the closure to the object and invoke it

(Anonymous functions in PHP are called closures.)

Ex. :


      
    $lang='ch';
    class Student {}if ($lang= ='ch') {
        $fun = function () {
            echo 'I am a student';
        };
    }
    else {
        $fun = function () {
            echo 'i am a student';
        };
    }

    / / binding
    $stu = new Student;
    $fun->call($stu)
? >
Copy the code

Effect:

7. Exception handling

Focus on handling exceptions that occur within a code block. If an exception occurs in the code block, it is thrown directly. The exception is not handled in the code block, and the exception is handled together.

7.1 Keywords

Try: to detect a block of code catch: throw: to throw an Exception finally: to execute with or without an Exception

Grammatical structure:


      
    try {
        // Check the code
    }
    catch (Exception $ex) {
        // Catch an exception
    }
    finally {
        // Execute with or without an exception, finally can be omitted
    }
? >
Copy the code

7.2 sample

Examples:

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>

      
    if (isset($_POST['button']) {try {
            $age = $_POST['age'];
            if ($age= =' ') {
                throw new Exception('Age cannot be empty'); // Throw an exception
            }
            if(! is_numeric($age)) {
                throw new Exception('Age must be a number'); // Throw an exception
            }
            if(! ($age> =10 && $age< =30)) {
                throw new Exception('Must be between 10 and 30 years old'); // Throw an exception
            }
            echo 'You are the right age';
        }
        catch (Exception $ex) { // Catch an exception
            echo Error message:.$ex->getMessage(),'<br/>';
            echo Error code:.$ex->getCode(),'<br/>';
            echo 'File address:'.$ex->getFile(),'<br/>';
            echo 'Error line number:'.$ex->getLine(),'<br/>'; }}? >

<body>
    
    <form action="" method="post"<input type="text" name="age"><br/>
        <input type="submit" name="button" value="Submit">
    </form>
</body>
</html>
Copy the code

Effect:Note: When an exception is thrown, the try block terminates execution and gives execution permission to the catch block.

Custom exceptions

Scenario: How to implement sorting of exceptions? For example, there are three levels of exceptions and three ways to handle them. You can customize three types of exceptions.

The superclass of all exceptions is Exception, and methods in Exception are not allowed to be overridden. Ex. :

<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <title>Document</title>
</head>
<body>
    
      
    // Define a custom null exception class
    class MyNullException extends Exception {}

    // The user-defined type is abnormal
    class MyTypeException extends Exception {}

    // Custom scope exception
    class MyRangeException extends Exception {}

    // Logic code
    if (isset($_POST['button']) {try {
            $name=$_POST['name'];
            $age=$_POST['age'];
            if ($name= =' ') {
                throw new MyNullException('Name cannot be empty! ');
            }
            if ($age= =' ') {
                throw new MyNullException('Age can't be empty! ');
            }
            if(! is_numeric($age)) {
                throw new MyTypeException('Age must be a number! ');
            }
            if ($age < 10 && $age > 30) {
                throw new MyRangeException('Must be between 10 and 30 years old! ');
            }
            echo 'Name:'.$name.'<br/>';
            echo 'Age:'.$age.'<br/>';
        }
        catch (MyNullException $ex) {
            echo $ex->getMessage(),'<br/>';
            echo 'Errors logged';
        }
        catch (MyTypeException $ex) {
            echo $ex->getMessage(),'<br/>';
            echo 'Send email';
        }
        catch (MyRangeException $ex) {
            echo $ex->getMessage(),'<br/>';
            echo 'Contact administrator to modify'; }}? >
    <form action="" method="post"<input type="text" name="name"<br/> Age: <input type="text" name="age"><br/>
        <input type="submit" name="button" value="Submit">
    </form>
</body>
</html>
Copy the code

Effect:

On the way to learning PHP, if you find this article helpful to you, then please pay attention to like comment 3 times, thank you, your must be another support of my blog.