Home > Backend Development > PHP Tutorial > Summary of PHP object-oriented essentials_PHP tutorial

Summary of PHP object-oriented essentials_PHP tutorial

WBOY
Release: 2016-07-13 10:14:46
Original
708 people have browsed it

Summary of PHP object-oriented essentials

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

class B extends A
When declaring, B does not need to have the method in A
When calling:

$b=new B();
$b->Method() in A;
$b->Attributes in A=1;
$b->Method() in B;
$b->Method() in B;

If $a=new A();
Yes
$a->Method() in A;
$a->Attributes 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. 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

Attribute methods private cannot be inherited
The attribute method protected class is not visible outside and can be inherited
Class members defined by public property methods can be accessed from anywhere

3 Application of double colon:: in php

The "::" operator is often seen in PHP class code. This is a scope limiting operator, which is represented by a double colon "::". It is used to set the level of different scopes in the 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 by subclasses to override members and methods in parent classes.

The code is as follows:

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 parent::CONST_VALUE . "n";
echo self::$my_static . "n";
}
}

OtherClass::doubleColon();
//Subclass overrides parent class
class MyClass
{
protected function myFunc() {
echo "MyClass::myFunc()n";
}
}

class OtherClass extends MyClass
{
// Override the method in the parent class
Public function myFunc()
{
​​​​ //But the overridden method can still be called
        parent::myFunc();
           echo "OtherClass::myFunc()n";
}
}

$class = new OtherClass();
$class->myFunc();

4 The role of this, self and parent in php

this: 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 position in the hierarchy of 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.

. The code is as follows:

private static $firstCount = 0;
private $lastCount;

//Constructor
function __construct()
{
$this->lastCount = ++self:$firstCount; //Use self to call static variables. When calling self, you must use:: (field operation 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 code is as follows:

//Constructor of inherited class
function __construct( $personSex, $personAge )
{
​​​​​ parent::__construct( "test" ); //Use parent to call the constructor of the parent class
            $this->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 to 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 implicitly called. To execute the parent class's constructor, you need to call parent::__construct() in the child class's constructor.
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

父类 子类 结果
有构造函数 无构造函数 父构造
有构造函数 有构造函数 子构造



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 a characteristic of the interface;
3) When implementing multiple interfaces, methods in the interfaces cannot have duplicate names;
4) Interfaces 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 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)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}

          return $template;
}
}

9 attributes

The variable members of the class are called "properties". The property declaration starts with the keywords public or protected or private, and is followed by a variable. The variables in the 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 obtain
Get and assign its attributes, as well as "__isset()" to check attributes and "__unset()" to delete attributes.
To put it simply, one is for obtaining value and the other is for assigning 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 in the following way. Of course, you can also add them according to your personal style: //__get() method is used to obtain private attributes

The code is as follows:

class Person{
//The following are the member attributes of people
private $name; //Person’s name
private $sex; //person’s gender
private $age; //Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);}else {
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete private members
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->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, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

The code is as follows:

class Person{
//The following are the member attributes of people
private $name;
//Person’s name
private $sex;
//Person’s gender
private $age;
//Age of person
//__get() method is used to obtain private attributes
private function __get($property_name){
if(isset($this->$property_name)){
return($this->$property_name);
}else{
return(NULL);
}
}
}
//__set() method is used to set private attributes
private function __set($property_name, $value){
$this->$property_name = $value;
}
//__isset() method
private function __isset($nm){
echo "When the isset() function determines a private member, it is automatically called
";
return isset($this->$nm);
}
//__unset() method
private function __unset($nm){
echo "Automatically called when the unset() function is used outside the class to delete a private member
";
unset($this->$nm);
}
}
$p1=new Person();
$p1->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, the __unset() method is automatically called to help us complete the task and delete the name private attribute
unset($p1->name);
//It has been deleted, so there will be no output for this line
echo $p1->name;
?>

10 clones

Object copying can be completed 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 an object is copied, PHP5 will perform a "shallow copy" of all properties of the object. All references in the properties remain unchanged and point 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).

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/907713.htmlTechArticlePHP object-oriented summary 1 Use extends to implement inheritance, overloading, and the meaning of magic methods class B extends A declaration When there is no method in A in B, when calling: $b=new...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template