PHP object-oriented skills

Source: Internet
Author: User
1. Use extends to implement inheritance, overload, and magic methods. When classBextendsA is declared, $ bnewB () can be called in B without the method in (); $ B-A's method (); $ B-A's attribute 1; $ B-B's method (); if $ anewA (); You Can $ method () in a-A; $ attribute 1 IN a-A; not

1. Use extends to implement inheritance, overload, and magic methods. When class B extends A is declared, $ B = new B () can be used when method A in B is not called (); $ B-A's method (); $ B-A's attribute = 1; $ B-B's method (); if $ a = new A (); You Can $ a-A in the method (); $ a-A in the attribute = 1; not

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 ();

Heavy Load: B inherits method attributes of 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: 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 the constructor of the subclass.Parent: :__ construct ().

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 clipboardprint?

  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 class Person {// The following is the member attribute private $ name of a Person; // the name of a Person is private $ sex; // The Gender private $ age of a Person; // person's age // _ get () method is used to obtain the private property private function _ get ($ property_name) {if (isset ($ this-> $ property_name )) {return ($ this-> $ property_name);} else {return (NULL) ;}}// _ set () the private function _ set ($ property_name, $ value) {$ this-> $ property_name = $ value;} // _ isset () method private function _ isset ($ nm) {echo "is When the set () function is used to determine a private member, it is automatically called <br> "; 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 <br> "; 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 )). "<br>"; echo $ p1-> name. "<br>"; // when the unset () function is used to delete a private member, the _ unset () method is automatically called to help us complete the operation, delete the name private property unset ($ p1-> na Me); // The row does not output echo $ p1-> name;?>


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 ).

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.