PHP class and object full parsing (2)

Source: Internet
Author: User
PHP class and object full parsing (2) Directory

Full analysis of PHP classes and objects (1)

PHP class and object full parsing (2)

PHP class and object resolution (3)

7. Static keywords


If the declared class member or method is static, you can directly access it without instantiating the class. You cannot access static members through an object (except for static methods ).

Static members belong to the class and do not belong to any object instance, but the object instances of the class can be shared.
Summary:

Access static member attributes or methods within a class and use self: :( No $ symbol), for example:
Self: $ country // class internal access static member attributes
Self: myCountry ()
When a subclass accesses a static member attribute or method of the parent class, use parent: :( No $ symbol), for example:
Parent: $ country
Parent: myCountry ()
For external access, the static member attributes and methods are class name/subclass name:, for example:
Person: $ country
Person: myCountry ()
Student: $ country
However, static methods can also be accessed through common objects.

    
 ";}} Class Student extends Person {function study () {echo" I am ". parent: $ country." Person
";}} // Output member property value echo Person: $ country ."
"; // Output: China $ p1 = new Person (); // echo $ p1-> country; // incorrect syntax // access static member method Person :: myCountry (); // output: I am a Chinese user // The static method can also be accessed through an object: $ p1-> myCountry (); // echo Student :: $ country."
"; // Output: China $ t1 = new Student (); $ t1-> study (); // output: I am a chinese?>

---------------------------------------------------

8. abstract class PHP5 supports abstract classes and abstract methods.


An abstract class cannot be instantiated directly. you must first inherit this abstract class and then instantiate it.
An abstract class must contain at least one abstract method. If a class method is declared as abstract, it cannot include specific function implementations.
When inheriting an abstract class, the subclass must implement all abstract methods in the abstract class;
In addition, the visibility of these methods must be the same (or more relaxed) as in the abstract class ).
If an abstract method in an abstract class is declared as protected, the implemented method in the subclass should be declared as protected or public, but cannot be defined as private.
// Abstract method: abstract protected function getValue ();
Example 1

Abstract class AbstractClass {// define the abstract method abstract protected function getValue (); // common method public function printOut () {print $ this-> getValue ()."
";}} Class ConcreteClass extends AbstractClass {protected function getValue () {return" abstract "; // implementation of abstract methods }}$ class1 = new ConcreteClass; $ class1-> printOut ();

Example 2

Abstract class AbstractClass {// force the subclass to define these methods abstract protected function getValue (); abstract protected function prefixValue ($ prefix); // common method (non-abstract method) public function printOut () {print $ this-> getValue (). "\ n" ;}} class ConcreteClass1 extends AbstractClass {protected function getValue () {return "ConcreteClass1";} public function prefixValue ($ prefix) {return "{$ prefix} ConcreteClass1";} class ConcreteClass2 extends AbstractClass {public function getValue () {return "ConcreteClass2";} public function prefixValue ($ prefix) {return "{$ prefix} ConcreteClass2" ;}}$ class1 = new ConcreteClass1; $ class1-> printOut (); echo $ class1-> prefixValue ('foo _'). "\ n"; $ class2 = new ConcreteClass2; $ class2-> printOut (); echo $ class2-> prefixValue ('foo _'). "\ n ";

/*
* An abstract class cannot be directly instantiated. you must first inherit this abstract class and then instantiate it.
An abstract class must contain at least one abstract method. If a class method is declared as abstract, it cannot include specific function implementations.
When inheriting an abstract class, the subclass must implement all abstract methods in the abstract class;
In addition, the visibility of these methods must be the same (or more relaxed) as in the abstract class ).
If an abstract method in an abstract class is declared as protected, the implemented method in the subclass should be declared as protected or public, but cannot be defined as private.
*
*/

    class Person {          public $name;          public $age;                function say() {              echo "my name is:".$this->name."
"; echo "my age is:".$this->age; } }

// Class inheritance

Class Student extends Person {var $ school; // attribute function study () {echo "my name is:". $ this-> name ."
"; Echo" my shool is :". $ this-> school ;}}$ t1 = new Student (); $ t1-> name = "zhangsan"; $ t1-> school = "beijindaxue "; $ t1-> study ();

---------------------------------------------------------------------


9. Interface


Interface Definition: a set of methods and constant value definitions
Using interfaces to define an interface is like defining a standard class, but defining all methods is empty.

Interface features: all methods defined in the interface must be public

Interface implementation: an interface can use the implements operator. the class must implement all methods in the interface. Otherwise, a fatal error is reported. if you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces.

Differences between abstract classes and interfaces

An interface is a special abstract class and can also be seen as a model specification. The interface and abstract class are roughly different as follows:

1. if a subclass implements an interface, all methods in the interface must be implemented (whether or not required); if an abstract class is inherited, you only need to implement the required methods.
2. if the method name defined in an interface is changed, all subclasses implementing this interface must synchronously update the method name. if the method name in the abstract class is changed, the method name corresponding to its subclass is not affected, but is changed to a new method (relatively old method implementation ).
3. abstract classes can only be inherited. interfaces must be used when a subclass needs to implement functions inherited from multiple parent classes.
Instance 1:
// Declare an 'itemplate 'interface

nterface 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;          }      }  

Instance 2:
// Define the interface

    interface User{           function getDiscount();           function getUserType();       }  

// VIP user interface implementation

Class VipUser implements User {// VIP User discount coefficient private $ discount = 0.8; function getDiscount () {return $ this-> discount;} function getUserType () {return "VIP user" ;}} class Goods {var $ price = 100; var $ vc; // defines the User interface type parameter, at this time, you do not know what User function run (User $ vc) {$ this-> vc = $ vc; $ discount = $ this-> vc-> getDiscount (); $ usertype = $ this-> vc-> getUserType (); echo $ usertype. "goods Price :". $ this-> price * $ discount;} display-> run (new VipUser); // it can be another user type

-------------------------------------------------------------


10. overload


Definition: a method in a class has the same name as another method, but different parameters.
Under what conditions will heavy load be executed? When an attribute or method that is not defined in the current environment is called, or invisible in the current environment is called.

Tip:
If the final keyword is used when the parent class defines the method, the quilt class method is not allowed to overwrite.

Method for accessing the parent class to be overwritten
You can use the parent: Symbol to access the methods or member attributes covered by the parent class:
// PHP overload method _ call ()

_ Call () (Method overloading)
To avoid errors when the called method does not exist, use the _ call () method. This method is automatically called when the called method does not exist, and the program continues to execute.

Syntax:
// _ Call () method overload

    class Test{          public function __call($name,$args){           if($name== 'null' && count($args)==2 ){            $type='num';         foreach($args as $key => $val){             if(!(is_int($val) || is_float($val))){              $type= 'string';          }         }         $method=$name.ucfirst($type);         if(method_exists($this,$method),$args){             call_user_func_array(array($this,$method),$args);         }        }       }       public addNum($i,$j){           echo $i+$j;       }              public addString($i,$j){           echo $i.$j;       }      }      $test =new Test();      $test->add(3,4);      $test->add(3,'4');         

Case:

Class MemberTest {private $ data = array (); // The overloaded data is saved in public $ declared = 1; /** The overload cannot be used in the defined attribute */private $ hidden = 2;/** only when this attribute is accessed from outside the class, */public function _ set ($ name, $ value) {echo "Setting '$ name' to' $ value' \ n "; $ this-> data [$ name] = $ value;} public function _ get ($ name) {echo "Getting '$ name' \ n "; if (array_key_exists ($ name, $ this-> data) {return $ this-> data [$ name] ;}$ trace = debug _ Backtrace (); trigger_error ('undefined property via _ get ():'. $ name. 'In '. $ trace [0] ['file']. 'On Line '. $ trace [0] ['line'], E_USER_NOTICE); return null;}/** PHP 5.1.0 or later */public function _ isset ($ name) {echo "Is '$ name' set? \ N "; return isset ($ this-> data [$ name]);}/** PHP 5.1.0 or later */public function _ unset ($ name) {echo "Unsetting '$ name' \ n"; unset ($ this-> data [$ name]);}/** non-magic method */public function getHidden () {return $ this-> hidden;} echo"
\n";            $obj = new MemberTest;            $obj->a = 1;      echo $obj->a . "\n\n";            var_dump(isset($obj->a));      unset($obj->a);      var_dump(isset($obj->a));      echo "\n";            echo $obj->declared . "\n\n";            echo "Let's experiment with the private property named 'hidden':\n";      echo "Privates are visible inside the class, so __get() not used...\n";      echo $obj->getHidden() . "\n";      echo "Privates not visible outside of class, so __get() is used...\n";      echo $obj->hidden . "\n";  

// Attribute overload :__ set () ,__ get () ,__ isset () ,__ unset ()

    class Person{          private $data =array();          function __set($name,$value){           $this->data[$name]=$value;       }       function __get($name){           return $this->data[$name];       }      }  

Bytes -----------------------------------------------------------------------------------


11. object iteration


PHP5 provides an iteration object function. just like using an array, you can use foreach to traverse attributes in an object.

    class MyClass      {          public $var1 = 'value 1';          public $var2 = 'value 2';          public $var3 = 'value 3';                protected $protected = 'protected var';          private   $private   = 'private var';                function iterateVisible() {             echo "MyClass::iterateVisible:\n";             foreach($this as $key => $value) {                 print "$key => $value\n";             }          }      }            $class = new MyClass();            foreach($class as $key => $value) {          print "$key => $value\n";      }      echo "\n";                  $class->iterateVisible();  

---------------------------------------------------------------------------


12. design mode: Factory mode and Singleton mode, Observer Mode, command chain mode and policy mode

The command chain mode sends messages, commands, and requests based on loosely coupled topics, or sends arbitrary content through a set of handlers. Each handler determines whether it can process the request.
If yes, the request is processed and the process stops. You can add or remove a handler for the system without affecting other handlers.


Factory model
Definition: Factory allows you to instantiate an object during code execution. It is called the factory model because it is responsible for "production" objects. The parameter of the factory method is the class name corresponding to the object you want to generate.

Factory mode syntax:

    
     

Factory model case:

    
  getName();            ?>  

Singleton
Define three elements: 1. a class can only have one instance. 2. you must create this instance. 3. you must provide this instance to the system.

Purpose: 1. if the system requires a class to globally control some configuration information, you can easily implement it using the Singleton mode.
2. the Singleton mode can avoid resource consumption by a large number of new operations ()
3. in a page request, debugging is easy, because all the code is concentrated in a class (such as database operation class). you can set hooks in the class and output logs to avoid var_dump everywhere.

Singleton is used to generate a unique object for a class. Database Connection is the most commonly used place. After an object is generated in Singleton mode, the object can be used by many other objects.
The single-piece mode is a design mode that we often use in development. with the PHP5 object-oriented feature, we can easily build an application of the single-piece mode, below are several implementation methods of the single-piece mode in PHP:

    class Stat{          static $instance = NULL;                    static function getInstance(){              if(self::$instance == NULL){                  self::$instance = new Stat();              }                            return self::$instance;          }              private function __construct(){          }              private function __clone(){          }                        function sayHi(){              return "The Class is saying hi to u ";          }      }                  echo Stat::getInstance()->sayHi();   

This is the most common way to return a unique class instance in a getInstance method.

With a slight modification to the example, you can generate a general method, as long as you call any class that you want to use a single piece.

    class Teacher{          function sayHi(){              return "The teacher smiling and said 'Hello '";          }                    static function getInstance(){              static $instance;                            if(!isset($instance)){                  $c = __CLASS__;                  $instance = new $c;              }                      return $instance;          }      }            echo Teacher::getInstance()->sayHi();   

The last one is to provide a singleton class, and then call the getInstance method to produce an instance for any class.

    class singleton{          function getInstance($class){              static $instances = array();              if(!array_key_exists($class,$instances)){                  $instances[$class] = &new $class;              }              $instance = $instances[$class];                            return $instance;          }      }            class People{          function sayHi(){              return 'Hello i am a people?';          }      }            echo "
"; echo singleton::getInstance('People')->sayHi();

Through these three methods, we can easily apply the single-piece mode. if we can combine the factory mode, it will make our programming more organized and efficient.
Bytes ---------------------------------------------------------------------------------------

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.