Home > Backend Development > PHP Tutorial > Construction, destruction and encapsulation in object-oriented php_PHP tutorial

Construction, destruction and encapsulation in object-oriented php_PHP tutorial

WBOY
Release: 2016-07-13 17:13:18
Original
1009 people have browsed it

The declaration of a constructor is the same as the declaration of other operations, except that its name must be __construct(). Encapsulation is to combine the properties and services of the object into an independent and identical unit, and to hide the internal details of the object as much as possible

Construction method and destructor method
Construction method:
Most classes have a special method called a constructor. When an object is created, it will automatically call the constructor, that is, when the new keyword is used to instantiate the object, the constructor will be automatically called.

The declaration of a constructor is the same as the declaration of other operations, except that its name must be __construct(). This is a change in PHP5. In previous versions, the name of the constructor must be the same as the class name. This can still be used in PHP5, but few people use it now. The advantage of this is that the constructor can be Independent of the class name, there is no need to change the corresponding constructor name when the class name changes. For backward compatibility, if there is no method named __construct() in a class, PHP will search for a constructor method written in php4 with the same name as the class name.

Format: function __construct ([parameter]) { ... ... }

Only one constructor can be declared in a class, but the constructor will only be called once every time an object is created. This method cannot be called actively, so it is usually used to perform some useful initialization tasks. For example, the corresponding properties are assigned initial values ​​when the object is created.

The code is as follows Copy code

//Create a human
class Person
{
//The following are the member attributes of people
var $name; //The person’s name
var $sex; //person’s gender
var $age; //Age of person

//Define a constructor parameter as name $name, gender $sex and age $age
Function __construct($name, $sex, $age)

//The $name passed in through the constructor is assigned an initial value to the member attribute $this->name
            $this->name=$name;                                                  //The $sex passed in through the construction method is assigned an initial value to the member attribute $this->sex
           $this->sex=$sex;                                            //The $age passed in through the construction method assigns an initial value to the member attribute $this->age
             $this->age=$age;                                                     }  

//This person’s way of speaking
Function say()

echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."";
}  
}

//Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age
$p1=new Person("Zhang San","Male", 20);
$p2=new Person("李思","女", 30);
$p3=new Person("王五","男", 40);

//The following accesses the speaking method in the $p1 object
$p1->say();
//The following accesses the speaking method in the $p2 object
$p2->say();
//The following accesses the speaking method in the $p3 object
$p3->say();

The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40

//Create a human
class Person

{

//The following are the member attributes of people
var $name; //The person’s name
var $sex; //Person’s gender
var $age; //The person’s age

//Define a constructor parameter as name $name, gender $sex and age $age
Function __construct($name, $sex, $age)
{
//The $name passed in through the construction method is assigned an initial value to the member attribute $this->name
           $this->name=$name;
//The $sex passed in through the construction method is assigned an initial value to the member attribute $this->sex
           $this->sex=$sex;
//The $age passed in through the construction method assigns an initial value to the member attribute $this->age
           $this->age=$age;
}

//This person’s way of speaking
Function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."";
}
}

//Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age
$p1=new Person("Zhang San","Male", 20);
$p2=new Person("李思","女", 30);
$p3=new Person("王五","男", 40);

//The following accesses the speaking method in the $p1 object
$p1->say();
//The following accesses the speaking method in the $p2 object
$p2->say();
//The following accesses the speaking method in the $p3 object
$p3->say();

The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40

Destructor:
The opposite of a constructor is a destructor. The destructor is a newly added content of PHP5. There is no destructor in PHP4. The destructor allows you to perform some operations or complete some functions before destroying a class, such as closing files, releasing result sets, etc. The destructor will be deleted when all references to an object are deleted or when the object is explicitly destroyed. When executed, that is, the destructor is called before the object is destroyed in memory. Similar to the name of the constructor, the name of a class's destructor must be __destruct(). The destructor cannot take any parameters.
Format: function __destruct ( ) { ... ... }

The code is as follows Copy code
//Create a human
 代码如下 复制代码
//创建一个人类  
class Person  
{  
    //下面是人的成员属性  
    var $name;  //人的名子  
    var $sex;    //人的性别  
    var $age;    //人的年龄  
 
    //定义一个构造方法参数为姓名$name、性别$sex和年龄$age  
    function __construct($name, $sex, $age)  
    {  
        //通过构造方法传进来的$name给成员属性$this->name赋初使值  
        $this->name=$name;  
        //通过构造方法传进来的$sex给成员属性$this->sex赋初使值  
        $this->sex=$sex;  
        //通过构造方法传进来的$age给成员属性$this->age赋初使值  
        $this->age=$age;  
    }  
 
    //这个人的说话方法  
    function say()  
    {  
        echo "我的名子叫:".$this->name." 性别:".$this->sex." 我的年龄是:".$this->age."";  
    }         
 
    //这是一个析构函数,在对象销毁前调用  
    function __destruct()  
    {  
        echo "再见".$this->name."";  
    }  
}  
 
//通过构造方法创建3个对象$p1、p2、$p3,分别传入三个不同的实参为姓名、性别和年龄  
$p1=new Person("张三","男", 20);  
$p2=new Person("李四","女", 30);  
$p3=new Person("王五","男", 40);  
 
//下面访问$p1对象中的说话方法  
$p1->say();  
//下面访问$p2对象中的说话方法  
$p2->say();  
//下面访问$p3对象中的说话方法  
$p3->say();  
 
输出结果为:  
 
我的名子叫:张三 性别:男 我的年龄是:20  
我的名子叫:李四 性别:女 我的年龄是:30  
我的名子叫:王五 性别:男 我的年龄是:40  
 
再见张三  
再见李四  
再见王五 
class Person { //The following are the member attributes of people var $name; //The person’s name var $sex; //person’s gender var $age; //Age of person //Define a constructor parameter as name $name, gender $sex and age $age Function __construct($name, $sex, $age) {  //The $name passed in through the constructor is assigned an initial value to the member attribute $this->name             $this->name=$name;                                                  //The $sex passed in through the construction method is assigned an initial value to the member attribute $this->sex            $this->sex=$sex;                                            //The $age passed in through the construction method assigns an initial value to the member attribute $this->age              $this->age=$age;                                                     }   //This person’s way of speaking Function say() {  echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."";                                                                    //This is a destructor, called before the object is destroyed Function __destruct() {  echo "Goodbye".$this->name.""; }   } //Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age $p1=new Person("Zhang San","Male", 20); $p2=new Person("李思","女", 30); $p3=new Person("王五","男", 40); //The following accesses the speaking method in the $p1 object $p1->say(); //The following accesses the speaking method in the $p2 object $p2->say(); //The following accesses the speaking method in the $p3 object $p3->say(); The output result is: My name is: Zhang San Gender: Male My age is: 20 My name is: Li Si Gender: Female My age is: 30 My name is: Wang Wu Gender: Male My age is: 40 Goodbye Zhang San Goodbye Li Si Goodbye Wang Wu


Encapsulation
Encapsulation is one of the three major characteristics of object-oriented programming. Encapsulation is to combine the properties and services of an object into an independent and identical unit, and to hide the internal details of the object as much as possible. It contains two meanings: 1. .Combines all the attributes and all services of the object to form an indivisible independent unit (i.e. object). 2. Information hiding, that is, hiding the internal details of the object as much as possible, forming a boundary (or forming a barrier) to the outside world, and retaining only a limited external interface to connect it with the outside.

The reflection of the principle of encapsulation in software is that it requires that parts other than the object cannot access the internal data (properties) of the object at will, thus effectively avoiding the "cross-infection" of external errors and enabling software errors to Localization greatly reduces the difficulty of error checking and troubleshooting.

Let’s use an example to illustrate. Suppose a person’s object has attributes such as age and salary. Such personal privacy attributes are not something that other people can obtain at will. If you don’t use encapsulation, then others can’t. You can get it if you know it, but if you encapsulate it, others will have no way to obtain the encapsulated attributes. Unless you tell it yourself, others will have no way to get it. For example, personal computers have a password, and you don't want others to log in at will and copy and paste it into your computer. Also, for objects like people, the attributes of height and age can only be increased by oneself, and cannot be assigned values ​​arbitrarily by others, etc.

As you can see from the above example, private members cannot be accessed externally, because private members can only be accessed within this object. For example, if the object $p1 wants to share its private attributes, in The say() method accesses private properties, which is fine. (No access control is added. The default is public and can be accessed from anywhere)


//The way this person can speak, speak his own private attributes, and you can also access private methods here

The code is as follows Copy code

//Use the private keyword to encapsulate properties and methods:
//Original members:
var $name; //The name of the declarant
var $sex; //Declare the gender of the person
var $age; //The age of the declarant
function run(){…….}

//Change to encapsulated form:
private $name; //Encapsulate the person’s name using the private keyword
private $sex; //Encapsulate the person’s gender using the private keyword
private $age; //Encapsulate the person’s age using the private keyword
private function run(){……} //Use the private keyword to encapsulate a person’s walking method

//Use the private keyword to encapsulate properties and methods:
//Original members:
var $name; //Declarant’s name
var $sex; //Declarer’s gender
var $age; //The age of the declarant
function run(){…….}

//Change to encapsulated form:
private $name; //Encapsulate the person’s name using the private keyword
private $sex; //Encapsulate the person’s gender using the private keyword
private $age; //Encapsulate the person’s age using the private keyword
private function run(){……} //Use the private keyword to encapsulate a person’s walking method. Note: As long as there are other keywords in front of the member attributes, the original keyword "var" must be removed. You can use private Encapsulates human members (member properties and member methods). The members in the encapsulation cannot be directly accessed outside the class, only within the object itself; the following code will generate an error:


class Person
{
//The following are the member attributes of people
Private $name; //The person’s name is encapsulated by private
Private $sex; //A person’s gender is encapsulated by private
Private $age; //A person’s age is encapsulated by private

//How this person can speak
Function say()

echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."";
                                                                  
//The way this person can walk is encapsulated privately
Private function run()

echo "This person is walking";
}  
}
//Instantiate a person’s instance object
$p1=new Person();

//Trying to assign a value to a private attribute will result in an error
$p1->name="Zhang San";
$p1->sex="Male";
$p1->age=20;

//Trying to print private attributes, an error will occur
echo $p1->name."";
echo $p1->sex."";
echo $p1->age.""

//Trying to print private member methods, an error will occur
$p1->run();

The output result is:
Fatal error: Cannot access private property Person::$name
Fatal error: Cannot access private property Person::$sex
Fatal error: Cannot access private property Person::$age
Fatal error: Cannot access private property Person::$name
Fatal error: Call to private method Person::run() from context ''

class Person

{
//The following are the member attributes of people
Private $name; //The person’s name is encapsulated by private
Private $sex; //A person’s gender is encapsulated by private
Private $age; //A person’s age is encapsulated by private

//How this person can talk

Function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."";
}  

//The way this person can walk is encapsulated privately

Private function run()
{
echo "This person is walking";
}
}
//Instantiate a person’s instance object
$p1=new Person();

// Trying to assign a value to a private attribute will result in an error

$p1->name="Zhang San";
$p1->sex="Male";
$p1->age=20;

//When trying to print private attributes, an error will occur

echo $p1->name."";
echo $p1->sex."";
echo $p1->age.""

//When trying to print private member methods, an error will occur

$p1->run();

The output result is:

Fatal error: Cannot access private property Person::$name
Fatal error: Cannot access private property Person::$sex
Fatal error: Cannot access private property Person::$age
Fatal error: Cannot access private property Person::$name
Fatal error: Call to private method Person::run() from context ''

The code is as follows Copy code

function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
//Private methods can also be accessed here
//$this->run();
}

//The method this person can speak, speak his own private attributes, and you can also access private methods here
function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
//Private methods can also be accessed here
//$this->run();
}Because the member method say() is public, it is okay for us to call the say() method outside the class. Change the above code;


class Person
{
//The following are the member attributes of people
Private $name; //The person’s name is encapsulated by private
Private $sex; //A person’s gender is encapsulated by private
Private $age; //A person’s age is encapsulated by private

//Define a constructor parameter to assign values ​​to the private attributes name $name, gender $sex and age $age
Function __construct($name, $sex, $age)

//The $name passed in through the constructor is assigned an initial value to the private member property $this->name
            $this->name=$name;                                                  //The $sex passed in through the constructor is assigned an initial value to the private member property $this->sex
           $this->sex=$sex;                                            //The $age passed in through the constructor is assigned an initial value to the private member property $this->age
             $this->age=$age;                                                     }  

//The way this person can speak, tell his own private attributes, and he can also access private methods here
Function say()

echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}  
}

//Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age
$p1=new Person("Zhang San", "Male", 20);
$p2=new Person("李思","女", 30);
$p3=new Person("王五","男", 40);

//The following accesses the speaking method in the $p1 object
$p1->say();
//The following accesses the speaking method in the $p2 object
$p2->say();
//The following accesses the speaking method in the $p3 object
$p3->say();

The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40

class Person
{
//The following are the member attributes of people
Private $name; //The person’s name is encapsulated by private
Private $sex; //A person’s gender is encapsulated by private
Private $age; //A person’s age is encapsulated by private

//Define a constructor parameter to assign values ​​to the private attributes name $name, gender $sex and age $age
Function __construct($name, $sex, $age)
{
//The $name passed in through the constructor is assigned an initial value to the private member property $this->name
           $this->name=$name;
//The $sex passed in through the constructor is assigned an initial value to the private member property $this->sex
           $this->sex=$sex;
//The $age passed in through the constructor is assigned an initial value to the private member property $this->age
           $this->age=$age;
}

//The way this person can speak, speak his own private attributes, you can also access private methods here
Function say()
{
echo "My name is: ".$this->name." Gender: ".$this->sex." My age is: ".$this->age."
";
}
}

//Create three objects $p1, p2, $p3 through the construction method, and pass in three different actual parameters: name, gender and age
$p1=new Person("Zhang San", "Male", 20);
$p2=new Person("李思","女", 30);
$p3=new Person("王五","男", 40);

//The following accesses the speaking method in the $p1 object
$p1->say();
//The following accesses the speaking method in the $p2 object
$p2->say();
//The following accesses the speaking method in the $p3 object
$p3->say();

The output result is:
My name is: Zhang San Gender: Male My age is: 20
My name is: Li Si Gender: Female My age is: 30
My name is: Wang Wu Gender: Male My age is: 40 Because the constructor is the default public method (do not set the constructor to private), it can be accessed outside the class, so you can use the constructor Create an object, and the constructor is also a function in the class, so you can use the constructor to assign initial values ​​to private properties. The Say() method is public by default, so it can be accessed from the outside to tell its own private properties.

From the above example, we can see that private members can only be used inside the class and cannot be directly accessed by outside the class. However, they have permission to access inside the class, so sometimes we need to Assigning and reading private properties outside the class means providing some accessible interfaces outside the class. In the above example, the constructor method is a form of assignment, but the constructor method only assigns values ​​when the object is created. If We already have an existing object and want to assign a value to this existing object. At this time, if you also use the constructor method to pass a value, then a new object will be created, not the existing object. . Therefore, we need to make some interfaces for private attributes that can be accessed externally. The purpose is to change and access the value of the attribute when the object exists. However, it should be noted that this can only be done for attributes that need to be changed externally. Properties that do not want to be accessed by the outside do not have such an interface, so that the purpose of encapsulation can be achieved. All functions are completed by the object itself, providing as few operations as possible to the outside world.

If you provide an interface outside the class, you can provide setting methods and get methods for private properties outside the class to operate the private properties. For example:

//Private attribute age prvate $age;
The code is as follows
 代码如下 复制代码

//私有的属性年龄  
prvate $age;  
 
//为外部提供一个公有设置年龄的方法  
function setAge($age)  
{  
    //在给属性赋值的时候,为了避免非法值设置给属性  
    if($age<0 || $age>130)  
        return;  
    $this->age=$age;  
}  
 
//为外部提供一个公有获取年龄的方法  
function getAge()  
{  
    return($this->age);  

//私有的属性年龄
prvate $age;

//为外部提供一个公有设置年龄的方法
function setAge($age)
{
 //在给属性赋值的时候,为了避免非法值设置给属性
 if($age<0 || $age>130)
  return;
 $this->age=$age;
}

//为外部提供一个公有获取年龄的方法
function getAge()
{
 return($this->age);
}上

Copy code

//Provide a public method for setting age externally

function setAge($age)

{ If($age<0 || $age>130) Return; $this->age=$age; } //Provide a public method for obtaining age externally function getAge() { Return($this->age); }
//Private attribute age prvate $age;
//Provide a public method for setting age externally
function setAge($age) { //When assigning values ​​to attributes, in order to avoid setting illegal values ​​​​to the attributes if($age<0 || $age>130) return; $this->age=$age; } //Provide a public method for obtaining age externally function getAge() { return($this->age); }Up The above method is to set and get the value for a member attribute. Of course, you can also use the same method to assign and get the value for each attribute to complete the access work outside the class. http://www.bkjia.com/PHPjc/629193.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/629193.htmlTechArticleThe declaration of the constructor is the same as the declaration of other operations, except that its name must be __construct(), and the encapsulation is Combine the object's properties and services into a single, identical unit, and try to...
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