Inheritance analysis of PHP constructors

Source: Internet
Author: User
Tags constructor inheritance

Constructor usage

HP 5 Allowable developers define a method as a constructor in a class. Classes with constructors Call this method each time a new object is created, so it is ideal to do some initialization before working with the object.

Note: If a constructor is defined in a subclass, the constructor of its parent class is not implicitly invoked. To execute the constructor of the parent class, you need to call Parent::__construct () in the constructor of the subclass. If a subclass does not define a constructor, it inherits from the parent class as a normal class method (if it is not defined as private).
Example #1 using the new standard constructor

The code is as follows Copy Code

<?php
Class BaseClass {
   function __construct () {
       print "in Basec Lass Constructorn ";
  }
}

Class Subclass extends BaseClass {
   function __construct () {
&NBSP;&NBSP;&NBSP;&NBSP;&N bsp;  parent::__construct ();
       print "in subclass Constructorn";
  }
}

Class Othersubclass extends BaseClass {
   //Inherits BaseClass ' s constructor
}

//In BaseClass constructor
$obj = new BaseClass ();

//In BaseClass constructor
//In subclass constructor
$obj = new Subclass ();

//In BaseClass constructor
$obj = new Othersubclass ();
?

For backward compatibility, if PHP 5 cannot find the __construct () function in the class and does not inherit one from the parent class, it will try to find the legacy constructor, which is a function with the same name as the class. So the only scenario that will create a compatibility problem is when a method named __construct () already has a class in it that is used for other purposes.

Unlike other methods, PHP does not produce a e_strict error message when __construct () is overwritten with a method that has different parameters than the parent class __construct ().

From PHP 5.3.3, in a namespace, a method with the same name as a class name is no longer a constructor. This change does not affect classes that are not in the namespace.

Example #2 Constructors in namespaced classes

The code is as follows Copy Code

<?php
namespace Foo;
Class Bar {
Public Function Bar () {
Treated as constructor in PHP 5.3.0-5.3.2
Treated as regular method as of PHP 5.3.3
}
}
?>

The initial value is assigned when the object is built.

The code is as follows Copy Code
1.//Create a human
2.
3.0class person
4.0{
5.//Below is the member property of the person
6. var $name; The name of a man
7. var $sex; The gender of the person
8. var $age; The age of the person
9.//Define a constructor method parameter for name $name, gender $sex and age $age
function __construct ($name, $sex, $age)
11. {
12.//Through the construction method $name to the member property $this->name the first value
$this->name= $name;
14.//Through the construction method $sex to the member property $this->sex the first value
$this->sex= $sex;
16.//Through the construction method $age to the member property $this->age the first value
$this->age= $age;
18.}
19.//This person's way of speaking
function Say ()
21. {
echo "My name is called:" $this->name. "Sex:". $this->sex. "My Age is:". $this->age. " <br> ";
23.}
24.}
25.//Create 3 objects through the construction method $p1, P2, $p 3, passed into three different arguments for name, gender and age, respectively
$p 1=new person ("John", "Male", 20);
$p 2=new person ("Dick", "female", 30);
$p 3=new person ("Harry", "male", 40);
29.//below access to the $p1 object in the speech method
$p 1->say ();
31.//below access to the $p2 object in the speech method
$p 2->say ();
33.//below access to the $p3 object in the speech method
$p 3->say ();


The output results are:

My name is called: John Sex: Male My age is: 20
My name is called: Dick Sex: Female my age is: 30
My name is called: Harry Sex: Male My age is: 40

Inheritance problems for constructors

Let's look at a simple example:

The code is as follows Copy Code


<?php

Class Fruit {

Public function __construct ($name)

{

echo ' fruit '. $name. ' Created ';

}

}

Class Apple extends Fruit {

Public function __construct ($name)

{

Parent::__construct ($name);

}

}

$apple = new Apple ("Apple");

Output Fruit Apple has created

?>

The inheritance of the constructor saves the rewrite of the code, not the declaration of the method, that is, the constructor declared in the parent class must be declared again in the subclass, which is also a process of rewriting.

The constructor inheritance of PHP must meet the following conditions:

When the parent class has a constructor declaration, the subclass must also have a declaration, or there will be an error.
When you execute a constructor for a parent class, you must reference the parent keyword in the child class.
If the parent class has a constructor and the subclass has no constructors, the parent class constructor is indeed executed when the subclass is instantiated. For example, suppose the employee class has the following constructor:

The code is as follows Copy Code

function __construct ($name) {

$this->setname ($name);

}
Then instantiate the CEO class and get its name member:


$ceo = new CEO ("Gonn");

echo $ceo->getname ();
The following results will be obtained:


My name is Gonn

However, if a subclass also has a constructor, the subclass's own constructor is executed when the subclass is instantiated, regardless of whether the parent class has a constructor. For example, suppose that in addition to the employee class containing the constructor above, the CEO class also contains the following constructors:

The code is as follows Copy Code

function __construct () {

echo "CEO object created!";

}

Then instantiate the CEO class and execute the GetName () in the same way, this time with a different output:


CEO Object created!

My name is Gonn
When Parent::__construct () is encountered, PHP starts searching for the appropriate constructor along the parent class. Because it was not found in executive, the search continued to know the employee class, where the appropriate constructor was found. If PHP finds a constructor in the employee class, it executes the constructor. If you want to execute both the employee constructor and the executive constructor, you need to call Parent::__construct () in the executive constructor.

Alternatively, you can select a different way to reference the constructor of the parent class. For example, suppose that when you create a new CEO object, both the employee and the executive constructors are executed. As mentioned above, these constructors can be referenced in the CEO's constructor, as follows:

The code is as follows Copy Code


function __construct ($name) {

Employee::__constrcut ($name);

Executive::__construct ();

echo "CEO object created!";
}

constructor inheritance in different PHP versions

References in constructors


PHP 4.x has the same constructor name as the class name.
The constructor name of the subclass is the same as the subclass name (nonsense).
The constructor of a parent class in a subclass is not executed automatically.
To perform the constructor of a parent class in a subclass, you must execute a statement similar to the following:
$this->[The constructor name of the parent class ()]

For example:

The code is as follows Copy Code

Class Base1
{
function Base1 ()
{
Echo ' This is base1 construct ';
}
}

class Class1 extends Base1
{
function Class1 ()
{
$this->base1 ();
Echo ' This is Class1 construct ';
}
}
$c 1 = new Class1;

php5.x version:

PHP5.0 the above version of the function of the class has been greatly expanded. The constructors for a class are named __construct ().
The constructor name of the subclass is also __construct () (also nonsense).
Whether the constructor of a parent class is executed in a subclass is divided into two situations:
1, if the subclass does not define a constructor __construct (), the constructor of the parent class is inherited by default and is executed automatically.
2, as the subclass defines the constructor __construct (), because the constructor name is also __construct (), the constructor of the subclass is actually overriding (override) The constructor of the parent class. The constructor for the subclass is executed.
In this case, if you want to execute the constructor of the parent class in a subclass, you must execute a statement similar to the following:

Parent::__construct ();

For example:

The code is as follows Copy Code

Class Base2
{
function __construct ()
{
Echo ' This is BASE2 construct ';
}
function __destruct ()
{
}
}

Class Class2 extends Base2
{
function __construct ()
{
Parent::__construct ();
Echo ' This is Class2 construct ';
}
}

Note Parent::__construct (); Statements must not necessarily be placed in the constructor of a subclass. The constructor of a subclass only guarantees that it is executed automatically when the subclass is instantiated.

Compatibility issues with PHP4.0 and class 5.0 constructors:

In the PHP5.0 version, the definition rules for the 4.0 version of the constructor are also compatible. If 4.0 constructors and __construct () functions are defined at the same time, the __construct () function takes precedence.
In order for the class code to be compatible with PHP4.0 and 5.0 at the same time, you can take the following ways:

The code is as follows Copy Code

Class Class3
{
function __construct ()//for PHP5.0
{
Echo ' This is Class2 construct ';
}

function Class3 ()//for PHP4.0
{
$this->__construct ();
}
}

$c 3 = new Class3;

The contents of the reference in the PHP constructor.

The code is as follows Copy Code
<?php
Class Foo {
function Foo ($name) {

Global $globalref;
$globalref [] = & $this;

$this->setname ($name);

$this->echoname ();
}
function Echoname () {
echo "<br/>", $this->name;
}
function SetName ($name) {
$this->name = $name;
}
}
?>

Check here for the difference between the $bar 1 created with the copy operator = and the $bar 2 created with the reference operator =& ... There is obviously no difference between
Copy to Clipboard
, but there is actually a very important difference: $bar 1 and $globalref [0] are not referenced, they are not the same variable. This is because "new" does not return a reference by default, but returns a copy.

The code is as follows Copy Code
<?php
$bar 1 = new Foo (' Set in constructor ');
$bar 1->echoname ();
$globalref [0]->echoname ();
/* & #36755;& #20986;& #65306;
Set in constructor
Set in constructor
Set in constructor * *
$bar 2 =& New Foo (' Set in constructor ');
$bar 2->echoname ();
$globalref [1]->echoname ();
/* & #36755;& #20986;& #65306;
Set in constructor
Set in constructor
Set in constructor * *
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.