PHP object-oriented essence

Source: Internet
Author: User
: This article mainly introduces the PHP object-oriented Essence. if you are interested in the PHP Tutorial, you can refer to it. 1. use extends to implement inheritance and the meanings of the overloaded and magic methods

Class B extends

The method in A can be absent from B during declaration.

$ B = new B ();

$ B-> method () in ();

$ B-> attribute in A = 1;

$ B-> method () in B ();

$ B-> method () in B ();

If $ a = new ();

Yes

$ A-> method () in ();

$ A-> attribute in A = 1;

No

$ A-> method () in B ();

$ A-> method () in B ();

Overload: B inherits the method attributes with the same name as A in A and B.

PHP's "overload" is different from most other object-oriented languages. The traditional "overload" is used to provide multiple class methods with the same name, but the parameter types and numbers of each method are different.

Magic method: PHP treats all class methods starting with _ (two underscores) as magic methods. Therefore, when you define your own class methods, do not use _ as the prefix.

2 inherit the access modifier visibility with private and protected

Attribute method private cannot be inherited

Property method: the protected class is invisible and can be inherited.

The class members defined by the attribute method public can be accessed anywhere.

3. application of double colon: in php

In php code, we often see the ":" operator, which is a limited scope operator. it is represented by a double colon ":", which is used to pin the levels of different scopes in the class. On the left is the access scope member on the right of the scope.

The scope defined in php is self and parent (static scope is provided in php6 ).

The range resolution operator (also known as Paamayim nekudow.im) or, more simply, a colon can be used to access static members, methods, and constants. It can also be used to override members and methods in the parent class by subclass.

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 overwrites the parent class

Class MyClass
{
Protected function myFunc (){
Echo "MyClass: myFunc () \ n ";
}
}
Class OtherClass extends MyClass
{
// Override the methods in the parent class
Public function myFunc ()
{
// But you can still call the overwritten method
Parent: myFunc ();
Echo "OtherClass: myFunc () \ n ";
}
}
$ Class = new OtherClass ();
$ Class-> myFunc ();

4. roles of this, self, and parent in php

This is the pointer to the current object instance, and does not point to any other object or class.

Self: indicates the scope of the current class. Unlike this, self does not represent a specific instance of the class and cannot be used in code outside the class, in addition, it cannot identify its position in the hierarchy of inheritance. That is to say, when self is used in an extension class, it calls not the method of the parent class, but the method of overloading the extension class. Self points to the class itself, that is, self does not point to any instantiated object. Generally, self points to static variables in the class.

Private static $ firstCount = 0;
Private $ lastCount;
// Constructor
Function _ construct ()
{
$ This-> lastCount = + self: $ firstCount; // to use self to call static variables, you must use: (domain operator number)
}

Parent: indicates the scope of the current class parent class, and the rest are the same as the self feature. Parent is a pointer to the parent class. generally, we use parent to call the constructor of the parent class.

// Constructor of the inherited class
Function _ construct ($ personSex, $ personAge)
{
Parent: :__ construct ("test"); // uses parent to call the constructor of the parent class.
$ This-> personSex = $ personSex;
$ This-> personAge = $ personAge;
}

5. constructor and Destructor

Classes with constructors call this method each time an object is created, so it is very suitable for initialization before using the object.

Function _ construct (){}
If the constructor is defined in the subclass, the constructor of its parent class will not be called secretly. To execute the constructor of the parent class, you must call parent ::__ construct () in the constructor of the subclass ().

PHP 5 introduces the concept of destructor, which is similar to other object-oriented languages, such as C ++. The Destructor is executed when all references to an object are deleted or when the object is explicitly destroyed.

Function _ destruct (){}

6 final keywords

PHP 5 adds a final keyword. If the method in the parent class is declared as final, the subclass cannot overwrite the method. if a class is declared as final, it cannot be inherited.

7. Inheritance and constructor

Parent class Subclass Result
Constructor No constructor Parent structure
Constructor Constructor Sub-structure

8 interfaces

You can use interfaces to define an interface, just like defining a standard class.

Note:

1) but all the methods defined in the definition are empty;

2) all methods defined in the interface must be public, which is a feature of the interface;

3) when multiple interfaces are implemented, the methods in the interfaces cannot have duplicate names;

4) interfaces can also be inherited by usingExtendsOperator;

5) constants can also be defined in the interface. The use of interface constants and class constants is identical. They are all set values and cannot be modified by the quilt class or subinterface.

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

// Implementation interface
// The following statements are 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 member of the class is called "attribute", and the attribute declaration is composed of keywords.PublicOrProtectedOrPrivateAnd a variable. The variables in the property can be initialized, but the initialization value must be a constant. the constant here means that the php script is a constant during compilation, instead of the constant calculated in the running phase after the compilation phase.

In PHP5, the two functions "_ get ()" and "_ set ()" are predefined to obtain
Take and assign values to its attributes, and check the attribute "_ isset ()" and the method "_ unset ()" for deleting the attribute ()".

In short, one is a value, and the other is a value ., The "_ set ()" and "_ get ()" methods do not exist by default, but are manually added to the class, like the constructor (_ construct (), the class will only exist after it is added. you can add these two methods in the following way. of course, you can also add them in your own style: // _ get () is used to obtain private attributes.

View plaincopy to clipboard

  1. Class Person {
  2. // The following are the member attributes of a person.
  3. Private $ name; // The name of a person.
  4. Private $ sex; // gender of a person
  5. Private $ age; // age of a person
  6. // _ Get () is used to obtain private attributes.
  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 () is used to set private attributes.
  15. Private function _ set ($ property_name, $ value ){
  16. $ This-> $ property_name = $ value;
  17. }
  18. // _ Isset () method
  19. Private function _ isset ($ nm ){
  20. When the echo "isset () function is used to determine private members, it is automatically called.
    ";
  21. Return isset ($ this-> $ nm );
  22. }
  23. // _ Unset () method
  24. Private function _ unset ($ nm ){
  25. Echo "automatically called when the unset () function is used outside the class to delete private members
    ";
  26. Unset ($ this-> $ nm );
  27. }
  28. }
  29. $ P1 = new Person ();
  30. $ P1-> name = "this is a person name ";
  31. // When the isset () function is used to determine a private member, the _ isset () method is automatically called to help us complete the measurement. the returned result is true.
  32. Echo var_dump (isset ($ p1-> name ))."
    ";
  33. Echo $ p1-> name ."
    ";
  34. // When the unset () function is used to delete a private member, the _ unset () method is automatically called to help us complete the deletion.
  35. Unset ($ p1-> name );
  36. // The row has been deleted and no output exists.
  37. Echo $ p1-> name;
  38. ?>

[Php] view plaincopy

  1. $ Property_name) {return ($ this-> $ property_name);} else
  2. {Return (NULL) ;}}// _ set () is used to set the private property private function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value;} // _ isset () method private function _ isset ($ nm) {echo "isset () this function is automatically called when determining 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
    "; Unset ($ this-> $ nm) ;}$ p1 = new Person (); $ p1-> name =" this is a person name "; // when the isset () function is used to determine private members, the _ isset () method is automatically called to help us complete the measurement, returns true echo var_dump (isset ($ p1-> name ))."
    "; Echo $ p1-> name ."
    "; // When the unset () function is used to delete a private member, the _ unset () method is automatically called to delete the private property of name.
  4. Unset ($ p1-> name); // The row has been deleted and no echo $ p1-> name;?> is output.


10 clone

Object replication can be completed by using the clone keyword (if the _ clone () method exists in the object, it will be called first ). The _ clone () method in the object cannot be called directly.

After an object is copied, PHP5 performs a shallow copy operation on all attributes of the object ). The references in all attributes remain unchanged and point to the original variables. If the _ clone () method is defined, the _ clone () method in the newly created object (copying the generated object) will be called, can be used to modify the attribute value (if necessary ).

11 php reference

Add the & symbol before variables, functions, and objects.


The reference in PHP means that different names access the same variable content.
The pointer in the C language is different from the pointer in the C language. the pointer in the C language stores the address where the variable content is stored in the memory.
Variable reference
PHP reference allows you to use two variables to point to the same content
[Php]
$ A = "ABC ";
$ B = & $;
Echo $ a; // output here: ABC
Echo $ B; // output here: ABC
$ B = "EFG ";
Echo $ a; // Here, the value of $ a is changed to EFG, So EFG is output.
Echo $ B; // output EFG here
?>
[/Php]
Function address transfer call
I will not talk much about the address transfer call. the following code is provided directly.
[Php]
Function test (& $)
{
$ A = $ a + 100;
}
$ B = 1;
Echo $ B; // output 1
Test ($ B); // here, $ B actually transmits the memory address of the variable content of $ B to the function, you can change the value of $ B by changing the value of $ a in the function.
Echo"
";
Echo $ B; // output 101
[/Php]
Note that test (1); will cause an error.
Function Reference return
First look at the code
[Php]
Function & test ()
{
Static $ B = 0; // declare a static variable
$ B = $ B + 1;
Echo $ B;
Return $ B;
}
$ A = test (); // This statement outputs the value of $ B as 1.
$ A = 5;
$ A = test (); // This statement outputs the value of $ B to 2.
$ A = & test (); // This statement outputs the value of $ B to 3.
$ A = 5;
$ A = test (); // This statement outputs a value of 6 for $ B.
[/Php]
The following explains:
In this way, $ a = test (); is not actually returned by the function reference, which is no different from the normal function call. The reason is: this is the PHP rule.
PHP requires that $ a = & test (); is used to obtain the function reference and return.
As for what is reference return (in the PHP Manual, reference return is used when you want to use a function to find the variable on which the reference should be bound .) I haven't understood this sentence for a long time.
The example above is as follows:
$ A = test () is used to call a function. it only assigns the value of the function to $ a. any change made to $ a does not affect $ B in the function.
But how to call a function through $ a = & test, the function is to direct the memory address of the $ B variable in return $ B to the same place as the memory address of the $ a variable.
That is, the equivalent effect ($ a = & B;) is generated. Therefore, changing the value of $ a also changes the value of $ B.
$ A = & test ();
$ A = 5;
Later, the value of $ B is changed to 5.
Static variables are used to help you understand the reference and return functions. In fact, function reference and return are mostly used in objects.
Object reference
[Php]
Class {
Var $ abc = "ABC ";
}
$ B = new;
$ C = $ B;
Echo $ B-> abc; // output ABC here
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, object replication is implemented through reference. In the above column, $ B = new a; $ c = $ B; is equivalent to $ B = new a; $ c = & $ B;
In PHP5, the object is called by reference by default, but sometimes you may want to create a copy of the object and expect that the change of the original object will not affect the copy. for this purpose, PHP defines a special method called _ clone.
Role of reference
If the program is large, there are many variables that reference the same object, and you want to manually clear the object after it is used up, I suggest using the & method, then clear it in the form of $ var = null. in other cases, use the default php5 method. in addition, we recommend that you use the "&" method for transferring large arrays in php5 to save memory space.
Cancel reference
When you unset a reference, you just disconnect the binding between the variable name and the variable content. This does not mean that the variable content is destroyed. For example:
$ A = 1;
$ B = & $;
Unset ($ );
?>
Not unset $ B, just $.
Global Reference
When a variable is declared with global $ var, a reference to the global variable is actually created. That is to say, it is the same as doing so:
$ Var = & $ GLOBALS ["var"];
?>
This means that, for example, unset $ var does not unset global variables.
$ This
In the method of an object, $ this is always a reference to the object that calls it.
// Next is an episode
In php, the address pointing (similar to pointer) function is not implemented by the user, but is implemented by the Zend core. in php, the reference uses the principle of "copy at Write, unless a write operation occurs, the variables or objects pointing to the same address will not be copied.
In layman's terms
1: if the following code exists:
[Php]
$ A = "ABC ";
$ B = $;
[/Php]
In fact, both $ a and $ B point to the same memory address, not $ a and $ B occupy different memory.
2: Add the following code on the basis of the above code:
[Php]
$ A = "EFG ";
[/Php]
Because the memory data pointed to by $ a and $ B needs to be re-written, the Zend core automatically determines that $ B will generate a $ a data copy, apply for a new memory for storage

The above introduces the PHP object-oriented essence, including some content, and hopes to help those who are interested in PHP tutorials.

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.