Home >Backend Development >PHP Tutorial >PHP object-oriented essence

PHP object-oriented essence

WBOY
WBOYOriginal
2016-08-08 09:32:20898browse

1 Use extends to realize the meaning of inheritance, overloading and magic methods

class B extends A

When declaring, B does not need to have methods in A

When calling, $b=new B();

$b ->Method in A();

$b->Attribute in A=1;

$b->Method in B();

$b->Method in B( );

If $a=new A();

Yes

$a->Method in A();

$a->Attribute in A=1;

Not possible

$a->Method() in B;

$a->Method() in B;

Overloading: B inherits A, and B implements the method attribute with the same name as A.

"Overloading" in PHP is different from most other object-oriented languages. The traditional "overloading" is used to provide multiple class methods with the same name, but each method has different parameter types and numbers.

Magic methods: PHP treats all class methods starting with __ (two underscores) as magic methods. So when you define your own class methods, do not prefix them with __.

2 Inherit the visibility of private and protected access modifiers

Property methods private cannot be inherited

Property methods protected are not visible outside the class, but can be inherited

Property methods public The defined class members can be anywhere Visit

3 Applications of double colon:: in php

The "::" operator is often seen in PHP class codes. This is a scope-limiting operator, which is represented by a double colon "::". It is used The levels of different scopes in the sticky class. The left side is the scope and the right side is the members of the access scope.

There are two scopes defined in php: self and parent (static scope is provided in php6).

The scope resolution operator (also known as Paamayim Nekudotayim) or more simply a pair of colons can be used to access static members, methods and constants, and can also be used in subclassesto override parent classes members and methods .

class MyClass {
const
CONST_VALUE = 'A constant value';
}
echo
MyClass ::CONST_VALUE;

class OtherClass extends MyClass
{
public static
$my_static = 'static var';
public static function
doubleColon() {
                                                                                                                                                                                                                                           echo
::CONST_VALUE ."n"; echo n"
;
}}OtherClass ::doubleColon();


//Subclass overrides parent class
class MyClass{
       protected function

myFunc

" MyClass::myFunc()n"

; }}class
OtherClass
extends
MyClass
{
// Override methods in the parent class

public function
myFunc ()                                                                                                                                                                                       "OtherClass::myFunc()n"

4 this and self in php And the role of parent
this: It is a pointer to the current object instance, not to any other object or class.
self: Represents the scope of the current class. Unlike this, it does not represent a specific instance of the class. Self cannot be used in code outside the class, and it cannot identify its own hierarchical position in inheritance. That is to say, when self is used in an extended class, it does not call the method of the parent class, but the overloaded method of the extended class. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self is used to point to static variables in the class.

private static $firstCount = 0;
private $lastCount;
//Constructor function
function __construct()
lastCount = ++self:$firstCount; //Use self to call static variables, use The self call must use::(domain operator symbol)
          }

parent: Indicates the scope of the parent class of the current class, and the rest is the same as the self attribute. parent is a pointer to the parent class. Generally, we use parent to call the constructor of the parent class. // The constructor of the inheritance class

Function __ConStruct ($ Personsex, $ Personage) { Parent :: __ Construct ("test"); // Use Parent to call the parent-class constructor $ This- & GT; personSex = $personSex;

$this->personAge = $personAge;

}


5 Constructor and destructor

A class with a constructor will call this method first every time an object is created, so it is very suitable Do some initialization work before using the object.

function

__construct

() {}

If a constructor is defined in a subclass, the constructor of its parent class will not be called secretly. To execute the constructor of the parent class, you need to call

parent::__construct() in the constructor of the child class.
PHP 5 introduced the concept of destructors, similar to other object-oriented languages ​​such as C++. A destructor is executed when all references to an object are removed or when the object is explicitly destroyed.

function __destruct() {}

6 final keyword PHP 5 adds a new final keyword. If a method in the parent class is declared final, the subclass cannot override the method; if a class is declared final, it cannot be inherited.
7 Inheritance and constructor

Parent class

SubclassResultParent constructSubstructure
With constructor No constructor
With constructor There is a constructor

8 Interface

You can define an interface through interface, just like defining a standard class.

Note:

1) But all the methods defined in it are empty;

2) All methods defined in the interface must be public, which is the characteristic of the interface;

3) Implement multiple When there is an interface, the methods in the interface cannot have the same name;

4) The interface can also be inherited by using the

extends operator;

5) Constants can also be defined in the interface. Interface constants and class constants are used exactly the same. They are all fixed values ​​and cannot be modified by subclasses or subinterfaces.

//Declare an 'iTemplate' interface
interface iTemplate
{ Public function
setVariable($name, $var); public function
getHtml($template);}

// Implement the interface // The following writing is correct

class
Template implements iTemplate
{
      private 
$vars =array();
public function
setVariable($name, $var) {
$this
->vars[$name ] = $var; }
public function
getHtml
($template) ) {
                                                                                                                                          str_replace
('{' . $name . '}', $value,
$template); }} 9 Properties The variable members of the class are called "properties". The property declaration starts with the keyword public
or
protected
or private, and is followed by a variable. Variables in attributes can be initialized, but the initialized value must be a constant. The constant here refers to the constant that the PHP script is in the compilation stage, not the constant calculated in the running stage after the compilation stage.


In PHP5, two functions "__get()" and "__set()" are predefined to get and assign its attributes, as well as "__isset()" to check attributes and "__unset()" to delete attributes. )".

To put it simply, one is to get the value and the other is to assign the value. , the two methods "__set()" and "__get()", these two methods do not exist by default, but are manually added to the class. Like the constructor method (__construct()), they are added to the class. will exist. You can add these two methods as follows. Of course, you can also add them according to your personal style: //__get() method is used to get private attributes


view plaincopy to clipboard

  1. class Person{
  2. //The following are the member attributes of the person
  3. private $name; // The person’s name
  4. private $sex; //The person’s gender
  5. private $age; //Age of person
  6. //__get() method is used to get private properties
  7. private function __get($property_name){
  8. if(isset( $this->$property_name)){
  9. return($this->$property_name );}else {
  10. return(NULL);
  11. }
  12. }
  13. }
  14. //__set() method is used to set private properties
  15. private function __set($property_name, $value){
  16. $this->$property_name = $value;
  17. }
  18. //__isset() method
  19. private function __isset($nm){
  20. echo "isset() function When measuring private members, automatically call
    "
    ;
  21. return isset($this->$nm);
  22. }
  23. //__unset() method
  24. private function __unset($nm){
  25. echo "When using the unset() function outside the class to
    "
    ; automatically called when deleting a private member
  26. }
  27. $p1=newPerson();
  28. $p1
  29. ->name=
  30. "this is a person name"
  31. ;
  32. //Using isset () function automatically calls the __isset() method to help us complete it when measuring private members, and the return result is true
  33. echo
  34. var_dump(isset($p1->name)). "
    "
  35. ;
  36. echo
  37. $p1->name."
    "
    ; //Using unset() When the function deletes a private member, it automatically calls the __unset() method to help us complete the deletion of the name private attribute
  38. unset($p1->name); //has been deleted , so there will be no output for this line
  39. echo
  40. $p1->name;
  41. ?>
  42. [php] view plaincopy
    1. class Person{ //The following are the member attributes of the person private $name; //The name of the person private $sex; //The gender of the person private $age; //Person The age //__get() method is used to obtain private properties private function __get($property_name){ if(isset($this->$property_name)){ return($this->$property_name);}else
    2. { return(NULL); } } } //__set() method is used to set private properties private function __set($property_name, $value){ $this->$property_name = $ value; } //__isset() method private function __isset($nm){ echo "isset() function automatically calls when measuring private members
      "; return isset($this->$nm); } / /__unset() method private function
    3. __unset($nm){ echo" Automatically called when the unset() function is used outside the class to delete private members< br>"; unset($this->$nm); } } $p1=newPerson(); $p 1- >name="this is a person name"; //When using the isset() function to measure private members, the __isset() method is automatically called to help us complete it, and the return result is true echo var_dump(isset ($p1->name))."
      "; echo $p1->name."
      "; //When using the unset() function to delete private members, __unset(() is automatically called ) method to help us complete it, delete the name private attribute
    4. unset(
    5. $p1->name); //has been deleted, so there will be no output for this line echo $p1- >name; ?>
    10 Clone


    Object copying can be done through the clone keyword (if the __clone() method exists in the object, it will be called first). The __clone() method in an object cannot be called directly.

    When the object is copied, PHP5 will perform a "

    shallow copy

    " on all properties of the object. The references in all properties remain unchanged, pointing to the original variables. If the __clone() method is defined, the __clone() method in the newly created object (the object generated by copying) will be called and can be used to modify the value of the attribute (if necessary). 11 The reference of php

    is to add the & symbol in front of variables, functions, objects, etc.


    The meaning of quoting in PHP is: different names access the same variable content.
    is different from pointers in C language. CThe pointer in the language stores the address where the content of the variable is stored in memory
    Variable reference
    PHP’s reference allows you to use two variables to point to the same content
    [php]

    $a="ABC";
    $b =&$a;
    echo $a;//Output here: ABC
    echo $b;//Output here: ABC
    $b="EFG";
    echo $a;//The value of $a here becomes EFG, so EFG is output
    echo $b;//EFG is output here
    ?>
    [/php]
    function call-by-address
    I won’t go into details about the call-by-address. The code will be given directly below
    [php]
    function test(&$a)
    {
    $a=$a+100;
    }
    $b=1;
    echo $b;//Output 1
    test($b); //Here $b is passed What is given to the function is actually the memory address where the variable content of $b is located. By changing the value of $a in the function, the value of $b can be changed
    echo "
    ";

    echo $b ;//Output 101
    [/php]
    It should be noted that if test(1); is used here, an error will occur. Think about the reason yourself
    The reference return of the function
    Look at the code first
    [php]
    function &test()
    {
    static $b=0;//Declare a static variable
    $b=$b+1;
    echo $b;
    return $b;
    }
    $a=test();//This statement will output the value of $b as 1
    $a=5;
    $a=test() ;//This statement will output the value of $b as 2
    $a=&test();//This statement will output the value of $b as 3
    $a=5;
    $a =test();//This statement will output the value of $b as 6
    [/php]
    Explanation below:
    In this way, what $a=test(); actually gets is not The reference return of the function is no different from the ordinary function call. The reason is: This is the regulation of PHP
    PHP stipulates that the reference return of the function is obtained through $a=&test();
    As for what is a reference What about return (the PHP manual says: Reference return is used when you want to use a function to find which variable a reference should be bound to.) This nonsense made me unable to understand it for a long time
    Use the above example to explain it
    Calling a function using $a=test() only assigns the value of the function to $a, and any changes to $a will not affect $b in the function
    and through $a=&test( ) method to call a function, its function is to point the memory address of the $b variable in return $b and the memory address of the $a variable to the same place
    , which produces the equivalent of this effect ($a=&b ;) So changing the value of $a also changes the value of $b, so after executing
    $a=&test();
    $a=5;
    , the value of $b becomes 5
    Static variables are used here to let everyone understand the reference return of the function. In fact, the reference return of the function is mostly used in objects. a{
    var $abc="ABC";
    }
    $b=new a;
    $c=$b;
    echo $b->abc;//Output here ABC
    echo $c->abc;//Output ABC here
    $b->abc="DEF";
    echo $c->abc;//Output DEF here
    ?>
    [/php]
    The above code is the running effect in PHP5
    In PHP5, the copying of objects is achieved through references. In the above column, $b=new a; $c=$b; is actually equivalent to $b=new a; $c=&$b;
    The default in PHP5 is to call the object by reference, but sometimes you may want to Create a copy of an object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called __clone.
    The role of references
    If the program is relatively large, If there are many variables that refer to the same object, and you want to clear it manually after using the object, I personally recommend using the "&" method, and then using $var=null to clear it. In other cases, use the default method of php5. In addition, For the transfer of large arrays in php5, it is recommended to use the "&" method, after all, it saves memory space.
    Unreference
    When you unset a reference, you just break the binding between the variable name and the variable content. This does not mean that the variable contents are destroyed.For example:

    $a = 1;
    $b =& $a;
    unset ($a);
    ?>
    will not unset $b, just $a.
    global reference
    When declaring a variable with global $var you actually create a reference to the global variable. That is the same as doing:

    $var =& $GLOBALS["var"];
    ?>
    This means, for example, unset $var does not unset global variables.
    $this
    In a method of an object, $this is always a reference to the object that calls it.
    //Here’s another little episode
    The pointing (similar to pointer) function of the address in PHP is not implemented by the user himself, but is implemented by the Zend core. The reference in PHP uses "copy-on-write" The principle is that unless a write operation occurs, variables or objects pointing to the same address will not be copied.
    In layman terms
    1: If you have the following code
    [php]
    $a="ABC";
    $b=$a;
    [/php]
    In fact, $a and $b point to the same memory address at this time, instead of $a and $b occupying different memories
    2: If you add the following code to the above code
    [ php]
    $a="EFG";
    [/php]
    Since the data in the memory pointed to by $a and $b will be rewritten, the Zend core will automatically determine Produce a data copy of $a for $b and re-apply a piece of memory for storage

    The above has introduced the essence of object-oriented PHP, including aspects of content. I hope it will be helpful to friends who are interested in PHP tutorials.

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