(ii) PHP object-oriented theory 2

Source: Internet
Author: User
A Magic Method:
1. The Magic method begins with "__" and is the syntax sugar of PHP. Syntactic sugars are a more useful coding method or technique that makes code easier to read.
2. __set and __get
 
  $name = $value;    }    Public Function __get ($name) {        if (!isset ($this, $name)) {            echo ' no set ';            $this-$name = ' Set default value: ';        }            return $this $name;    }} $a = new account (), Echo $a-user;echo "

"; $a->user = 5;echo $a, $name; echo"

"; Echo $a->big;
If the __set and __get magic methods are defined in the class, then when assigning values or values to an object, neither the property nor the error will be made. Enhance the robustness of the program.
2.__call and __callstatic:
(The following code failed to execute successfully)
 fieldvalues[$fieldname];        } static function __callstatic ($method, $args) {$field = Preg_replace ('/^findby (\w*) $ ', ' ${1} ', $method);        $query = "SELECT * from". Static:: $table. "Where $field = ' $args [0]";    Return Self::createdomain ($query);        } private static function CreateDomain ($query) {echo "Test";        $klass = Get_called_class ();        $domain = new $klass ();        $domain->fieldvalues = Array ();        $domain->select = $query;        foreach ($klass:: $fields as $field = + $type) {$domain->fieldvalues[$field] = ' todo:set from SQL result ';    } return $domain;    }}class Customer extends activerecord{protected static $table = ' Custdb '; protected static $fields = array (' id ' = ' = ' int ', ' email ' = ' varchar ', ' lastname ' = ' varcha ')    R ');    Public Function __construct () {echo "* * *"; }}class Sales extends activerecord{protected static $table = ' sAlesdb '; protected static $fields = array (' id ' = ' = ' int ', ' item ' = ' varchar ', ' qty ' = ' = ' int ');}  ASSERT ("SELECT * from custdb where id = 123" = = Customer::findbyid (123)->select), assert ("Todo:set from sql result" = = Customer::findbyid (123)->email); Assert ("SELECT * from salesdb where id = 321" = = Sales::findbyid (321)->select); ASSERT ("SELECT * from custdb where LastName = ' Denoncourt '" = = Customer::findbylastname (' Denoncourt ')->select);
Use __call and __callstatic to ' prevent errors from calling methods that do not exist '. You can also make the dynamic creation of a method possible.
3.__tostring
 
  User}, the password is {$this->pwd} ";}    } $a = new account (); Echo $a; echo "

"; Echo Php_eol." = = = "; echo"


";p rint_r ($a);
In fact, the ToString method is also a way to serialize.
Two Inheritance and polymorphism:
1. Inheritance: There is a parent-child relationship between classes and classes that inherit the properties and methods of the parent class, called Inheritance.
In inheritance, subclasses have methods and properties of the parent class, and subclasses can have their own methods and properties.
 Name, "\tis", $this->gender, "\ r \ n";    }}class Family extends person{public $name;    Public $gender;    Public $age;    static $money = 100000;        Public Function __construct () {parent::__construct ();    echo "Here is the subclass", Php_eol; } public Function say () {echo '
I said ". $this->name," \tis\t ", $this->gender,", and is \ t ", $this->age,php_eol."
"; } Public Function Cry () {echo Parent:: $money, Php_eol; echo "%>-<%", Php_eol; echo Self:: $money, Php_eol; echo "(* ^_^ *)"; } public Function read () {echo '


Read again ". Parent::say ()."
"; }} $poor = new family (); $poor->name = ' Lee '; $poor->gender = ' female '; $poor->age =; $poor->say (); $poor Cry (); $poor->read (); * * Question: * I added a method on the subclass called Read * results are: * Here is the parent class here is the subclass I said Lee is Female,and is 2510000%>-<% 1000 XX (* ^_^ *) Lee Isfemaleread again why read again is behind Lee is female ... (I feel I should execute read again first) */

In inheritance, the parent is referred to as the parental class, and self refers to itself. Call the method of the parent class with "::" (scope resolution operator). The "::" operator is also used as a call to class constants and static methods.
If you declare a class member or method to be static, you can access it directly without instantiating the class.
A static member cannot be accessed through an object (except for static methods), or a non-static method can be accessed with "::".
Inheritance is a "yes, like" relationship, and a combination of a "need" relationship.
From the perspective of method reuse, if two classes have many of the same code and methods, you can abstract a parent class from these two classes, provide a public method, and then two classes as subclasses. Provide a personalized approach.
Inherited issues:
A. Inheritance destroys encapsulation.
B. Inheritance is tightly coupled.
C. inheritance extension complexity.
D. Improper use of inheritance may violate real-world logic.
 
  car = new Car;    }    Public Function Addoil () {        $this->car->addoil ();}    } $BMW = new BMW (), $BMW->addoil (); $benz = new Benz (); $benz->addoil ();
To use an inherited scenario:
A. The abstraction layer of the inheritance tree is generally not more than three layers.
B. Using the final modifier for classes that are not specifically used for inheritance can prevent important methods from overwriting.
C. Prioritizing composition relationships can improve the reusability of code.
D. Subclasses are a special type, not just a role of the parent class.
E. The underlying code is combined to improve efficiency, and the top level (business layer) code uses inheritance for greater flexibility.
2. Polymorphism:
In real development, you care about the programming of an interface or base class without having to care about the specific class that an object belongs to.
 
  Working ();    }} Doprint (new Teacher ());d Oprint (New Coder ());d Oprint (new Employee ());d Oprint (New Readbooks ());
Polymorphism can be achieved through an interface.
Summarize:
A. Polymorphism refers to the materialization of the same class of objects at run time
B. The PHP language is weakly typed, enabling polymorphism to be simpler and more flexible
C. Type conversions are not polymorphic
D. The parent and child classes in PHP are considered to be ' stepfather ' and ' stepson ' relationships, and there is an inheritance relationship. Subclasses cannot be transformed upward into a parent class.
E. The nature of polymorphism is if...else, but the level of implementation is different.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

The above is introduced (ii) PHP object-oriented theory 2, including the aspects of the content, I hope that the PHP tutorial interested in a friend helpful.

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