Object-oriented base of PHP code

Source: Internet
Author: User
Tags add object constructor inheritance interface php code what inheritance access

This article is not suitable for beginners to see, there is a certain understanding of PHP can look, add or warm up some of the characteristics of the PHP object-oriented.


What is Object oriented?

A problem, although inkling, but still feel not to take a shot, can only say that all things are seen as objects, only in the development can realize what is object-oriented, but also in vain, but because PHP is mostly used in web development, so, even if not using object-oriented also can run well, before doing in C + + development, Design to you a functional interface, see this interface, the first thing is like art Chettu cut into each object, and then, to determine the relationship between the objects, and finally to develop, where are filled with this idea.

What is a class? What is an object?

A class is an abstraction of a set of collections, what is a collection? is a set of objects with similar characteristics and actions.

An object is a specific instance of a class.

Graduation time may I will recite to the interviewer to listen to, but now, although feels understands still to want the book the statement same vulgar, but at least does not have to rely on the brain cell to say these two definitions.


Two. The class structure in PHP

The classes in PHP are also those access controllers, and they also have properties and methods.

Class Person {
    private $name = "PersonName";
    public static $gender = "Persongender";
    
    The Public Function test () {
        echo $this->name, '
'; } };


Three. Constructor function

The name of the constructor is __construct, and I would like to emphasize here the following points in the constructor:

1. PHP will not be like other languages (C + + or Java), when instantiating subclasses will automatically call your parent class constructor, PHP needs to manually call the parent class constructor, here involved in inheritance, you can first look at the inheritance aspect of things.

Class person{public
	Funciton __construct () {
		echo ' person construct
'; } }; Class Teacher extends person{public function __construct () { //parent::__construct (); Echo ' Teacher construct
'; } }; $t 1 = new Teacher; Generating teacher Objects

Run Result:

Teacher Construct

If you want to initialize some of the data for the parent class when you build the subclass, you need to manually invoke the parent class's constructor and open the comment line.


2. A class cannot write two constructors with different parameters.

This involves some of the rules in PHP, and in other languages, the following are the correct words:

Class person{public
	Funciton __construct () {
		echo ' person construct
'; } Public function __construct ($param) { echo ' person with Param construct
'; } };


And in PHP is not allowed, the root of the reason is that PHP is a weak language type, for the type of restrictions are not very sensitive, and thus provide the __call and Func_get_args function mechanism, and thus can be implemented in the following way:

Class person{public
	function __construct () {
		$param = Func_get_arg ();//Get parameter data
		$param _num = Func_num_args ( ); Gets the number of arguments
		if ($param _num = = 0) {
		}else if ($param _num = = 1) {
			if (is_array ($param [0])) {
				//...
			}
		} else{
			//...
		}}
;


Three. destructor

A destructor is a function that is invoked automatically at the end of this instance object to write a statement that frees memory to draw a perfect period for the death of an instance, where, as with the construct, there must be a manual invocation of the parent class's destructor, with only one destructor in a class.


Four. Control access character

Public: A common accessor, within a class, within a subclass, to which this property or method can be accessed.

Protected: A protected accessor that can only be accessed within a class and within its subclasses, and cannot be accessed outside of the class.

Privacy: Private access, can only be accessed within this category, belong to the private east, can not inherit, can not be overloaded, no one can access.


Five. Magic methods __get and __set

The functionality of these two methods: an accessor to a protected and private property that can be used to verify security and reasonableness of data received from outside the class.

The __set method receives two parameters, the first is the property name, and the second is the new value to be assigned.

The __get method receives a parameter, the property name.


1. The public property provides a service to modify the property outside of the class, so the __get and __set processes are not gone for the public property.

Class d{public
    $name = ' D name ';
    protected $gender = ' male ';
    Private $age =;

    Public Function __set ($name, $value) {
        echo ' __set
'; if (In_array ($name, [' Name ', ' gender ', ' age ']) $this-> $name = $value; } Public Function __get ($name) { echo ' __get
'; if (!in_array ($name, [' Name ', ' gender ', ' age ']) return NULL; return $this-> $name; } ;


Run Result:
The new D name//name is the public property and does not go to get and set
__set
__get
new D gender
__set __get
new D Age

2. We can also add data validation function, open the annotation can be verified.

3. Two methods must be public access, or you will be prompted with errors, we can start thinking from the function of these two functions, it is not difficult to imagine why public access control is required.


Six. Inheritance

Finally arrived can let your chrysanthemum open the characteristic of the bud, did not inherit, all class is slag, because has the inheritance, so ... The problem is a big wave of a big wave come ... Let's take a look at this inheritance feature.

What inheritance will not say it, the beginning of the article has a small example of inheritance.

What happens when you have an inheritance? Think about it, if B inherits a ... It's hard to imagine ...

1. Constructor, this rest assured, there is no relationship with inheritance, equivalent to two constructors in a class, but there is a father-son relationship, you can't do it too absolutely, so, as mentioned above, if you need to, you can manually call the parent class constructor, you can look at the example above.

2. Single direction inheritance, inherited in a single direction, subclasses can inherit from the parent class, but the parent class cannot inherit the attribute from the subclass, example:

Class a{public
	$attr 1;
	Public Function Oper1 () {
	}
};

Class B extends a{public
	$attr 2;
	Public Function Oper2 () {
	}
};
Subclasses can inherit the parent class
$b = new B;
$b->oper1 ();
$b->attr1 = ' attr1 value ';
$b->oper2 ();
$b->attr2 = ' attr2 value ';

The parent class cannot inherit subclasses
$a = new A;
$a->oper2 ()///Error
$a->attr1 ();

3. Overload, a reference to PHP overload is particularly awkward, because his overload in other languages called rewrite overwrite, I am still accustomed to this feature as a rewrite, everyone casually.

<1>public Overload:

Class e{public
    $attr 1 = ' E attr1 value ';
    Public Function Oper1 () {
        echo ' E oper1
'; Echo ' attr1 value = ', $this->attr1, '
'; } }; Class F extends e{public $attr 1 = ' F attr1 value '; Public Function Oper1 () { //parent::oper1 (); Echo ' F oper1
'; Echo ' attr1 value = ', $this->attr1, '
'; } }; $f = new F; $f->oper1 ();

Run Result:

F Oper1
ATTR1 value = F attr1 value


F inherits E and rewrites the ATTR1 and oper1 of E, so when Oper1 is invoked, $this->ATTR1 displays F attr1 value, and if you open the comment parent::oper1 invoke the Oper1 method of the parent class, the results are as follows:

E Oper1
ATTR1 value = F attr1 Value//attr1 property has been overridden by a quilt class Attr1 property overrides
F Oper1
ATTR1 value = F attr1 value

You can see that the subclass overrides the properties and methods of the parent class, overwriting the corresponding properties and methods of the parent class.


<2>private overload

Class e{
    private $attr 1 = ' E attr1 value ';
    Public Function Oper1 () {
        echo ' E oper1
'; Echo ' attr1 value = ', $this->attr1, '
'; } }; Class F extends e{public $attr 1 = ' F attr1 value '; Public Function Oper1 () { parent::oper1 (); Echo ' F oper1
'; Echo ' attr1 value = ', $this->attr1, '
'; } }; $f = new F; $f->oper1 ();
The above code only changes one place, is the parent class $ATTR1 access attribute becomes private, that overload mechanism how to carry out? First look at the results of the operation:

E Oper1
ATTR1 value = E ATTR1 value//Parent Class private Property
F Oper1
ATTR1 value = F attr1 value


As we have said before, private attributes and method subclasses are not inherited, and in this case, they follow a principle:

The private property is called in that class, showing the property value in which class.

The Parent::oper1 method in the example calls the Oper1 method of Class E, which in the Oper1 method of E also calls $THIS->ATTR1,ATTR1 is private and does not inherit from the quilt class, so it is called the Attr1 property value in Class E.


The <3>protected overload is consistent with the public overload


Inheritance of <4> class attributes

Class g{public
    static $attr 1 = ' G attr1 value ';
    Public Function Oper1 () {
        echo ' G oper1
'; Echo ' attr1 value = ', self:: $attr 1, '
'; } }; Class H extends g{public static $attr 1 = ' h attr1 value '; Public Function Oper1 () { parent::oper1 (); Echo ' H oper1
'; Echo ' attr1 value = ', self:: $attr 1, '
'; } }; $h = new H; $h->oper1 ();

Run Result:

G Oper1
ATTR1 value = G attr1 value
H Oper1
ATTR1 value = H attr1 value

In fact, whether the ATTR1 attribute of Class G is public or private, the results are the same.

Personally, the class attribute can inherit, but not overload, and there is a rule about the properties of a subclass calling the parent class:

Self or parent only represents this class, so it can be concluded from this principle that the value of the property must be the value of the property of this class, regardless of the subclass. (In special cases, PHP's static delay loading mechanism).


Seven. Static delay loading

Since the static delay loading has been mentioned, the iron Hot Talk, H and G examples have been seen, then I just want to call in the subclass of the parent class how to do? Static delay loading is the solution to this problem, see two examples:

Example 1:

Examples of classes H and G

Class g{public
    static $attr 1 = ' G attr1 value ';
    Public Function Oper1 () {
        echo ' G oper1
'; Echo ' attr1 value = ', static:: $attr 1, '
'; } }; Class H extends g{public static $attr 1 = ' h attr1 value '; Public Function Oper1 () { parent::oper1 (); Echo ' H oper1
'; Echo ' attr1 value = ', self:: $attr 1, '
'; } }; $h = new H; $h->oper1 ();
Run Result:

G Oper1
ATTR1 value = H attr1 value
H Oper1
ATTR1 value = H attr1 value

The code above simply rewrites self:: $attr 1 in the G class to static:: $attr 1, the results are different.


Example 2:

Class I {public
    static function-who ()
        {echo __class__, '
'; } public static function test () { static::who (); } }; Class J extends i{public static function who () { echo __class__, '
'; } };

Run Result:

J


With these two examples, you can take a good look at static delay binding.


Write a little more, mainly because one involved in the inheritance can not stop it .... Object-oriented There are some just points, there is time to make up after it ... Thank you, if there is the wrong place, please point out, at any time to correct, thank you!!





Related Article

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.