Full parsing of PHP classes and objects (ii)

Source: Internet
Author: User
Tags vars

Directory

Full parsing of PHP classes and objects (i)

Full parsing of PHP classes and objects (ii)

Full parsing of PHP classes and objects (iii)

7.Static keywords


Declaring a class member or method as static can be accessed directly without instantiating the class. Static members cannot be accessed through an object (except static methods).

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

To access static member properties or methods inside a class, use Self:: (without the $ symbol), such as:
Self:: $country//class internal access static member properties
Self:: Mycountry ()
To access the parent class static member property or method in the subclass, use Parent:: (without the $ symbol), such as:
Parent:: $country
Parent:: Mycountry ()
External access static member properties and methods are class name/subclass name::, such as:
Person:: $country
Person::mycountry ()
Student:: $country
However, static methods can also be accessed by ordinary objects

    
 
  ";          }      }      Class Student extends Person {          function study () {              echo "I am". Parent:: $country. " People
"; } } Output member property value echo Person:: $country. "
"; Output: China $p 1 = new person (); echo $p 1->country; Error notation //Access static Member Method Person::mycountry (); Output: I am Chinese //static methods can also be accessed by object: $p 1->mycountry (); Output member property values in subclasses echo Student:: $country. "
"; Output: China $t 1 = new Student (); $t 1->study (); Output: I am a Chinese ?>

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

8. Abstract classes PHP5 support abstract classes and abstract methods.


An abstract class cannot be instantiated directly, you must first inherit the abstract class, and then instantiate the subclass.
At least one abstract method should be included in the abstract class. If a class method is declared abstract, it cannot include a specific feature implementation.
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 looser) as in the abstract class.
If an abstract method in an abstract class is declared as protected, then the methods implemented in the subclass should be declared as protected or public, not private.
Abstract method: Protected function GetValue (), abstract;
Example 1

    Abstract class abstractclass{          //define abstraction method abstractly          protected function getValue ();          Common method Public          function PrintOut () {              print $this->getvalue (). "
"; } } Class Concreteclass extends abstractclass{ protected function GetValue () { return "abstract";//implementation of abstract methods } } $class 1 = new Concreteclass; $class 1->printout ();

Example 2

    Abstract class AbstractClass {//requires subclasses 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 () {R          Eturn "ConcreteClass2";          } Public Function Prefixvalue ($prefix) {return ' {$prefix}concreteclass2 ';      }} $class 1 = new ConcreteClass1;      $class 1->printout (); echo $class 1->prefixvalue (' Foo_ '). "            \ n "; $class 2 = new ConcreteClass2;      $class 2->printout (); echo $class 2->prefixvalue (' Foo_ '). "   \ n ";

/*
* Abstract classes cannot be instantiated directly, you must first inherit the abstract class, and then instantiate the subclass.
At least one abstract method should be included in the abstract class. If a class method is declared abstract, it cannot include a specific feature implementation.
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 looser) as in the abstract class.
If an abstract method in an abstract class is declared as protected, then the methods implemented in the subclass should be declared as protected or public, not private.
*
*/

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

Inheritance of Classes

    Class Student extends Person {          var $school;    Student's School attribute                    function study () {              echo "My name is:". $this->name. "
"; echo "My shool is:". $this->school; } } $t 1 = new Student (); $t 1->name = "Zhangsan"; $t 1->school = "Beijindaxue"; $t 1->study ();

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


9. Interface


Interface Definition: A collection of methods and constant value definitions
Defining an interface through interface is like defining a standard class, but all of the methods defined in it are empty.

Interface attribute: All methods defined in the interface must be public

Interface implementation: An interface can use the implements operator, the class must implement all the methods in the interface, otherwise the fatal error will be reported, if you want to implement multiple interfaces, you can use commas to separate the names of multiple interfaces.

The difference between an abstract class and an interface

An interface is a special abstract class and can also be seen as a specification of a model. Interfaces are roughly different from abstract classes:

1. A subclass if you implements an interface, you must implement all the methods in the interface (whether or not it is required), or if you are inheriting an abstract class, you only need to implement the required method.
2. If the method name defined in one of the interfaces changes, then all subclasses implementing this interface need to update the method name synchronously, whereas in an abstract class if the method name changes, the corresponding method names of its subclasses are not affected, but only become a new method (relatively old method implementation).
3. Abstract classes can only be inherited, and when a subclass needs to implement functionality that needs to inherit from more than one parent class, the interface must be used.
Example 1:
Declaring a ' iTemplate ' interface

Nterface iTemplate  {public      function setvariable ($name, $var);      Public Function gethtml ($template);  }  

Implementing interfaces
The following is the correct wording

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

Example 2:
Defining interfaces

    Interface user{           function Getdiscount ();           function Getusertype ();       }  

VIP User Interface Implementation

    Class Vipuser implements user{          //VIP user discount factor          private $discount = 0.8;          function Getdiscount () {              return $this->discount;          }          function Getusertype () {              return "VIP user";          }      }      Class goods{          var $price = +;          var $vc;          Defines the user interface type parameter, at which point it is not known what the Subscriber          function run (username $vc) {              $this->vc = $VC;              $discount = $this->vc->getdiscount ();              $usertype = $this->vc->getusertype ();              echo $usertype. " Goods Price: ". $this->price* $discount;          }      }            Display->run (new vipuser);    Can be more other user types  

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


10. Overloading


Definition: A method in one class has the same name as another method, but with different parameters
Under what circumstances do overloads execute? When a property or method is called that is not defined in the current environment, or when a property or method is called that is not visible under the current environment.

Tips:
If the parent class defines a method with the final keyword, the quilt class method is not allowed to overwrite.

Accessing the method that the parent class is overridden
The parent:: symbol can be used to access the method or member properties overridden by the parental class:
PHP overloaded Method __call ()

__call () (Method overloading)
To avoid errors when the calling method does not exist, you can use the __call () method to avoid it. The method will be called automatically when the calling method does not exist, and the program will continue to execute.

Grammar:
__call () method overloading

    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 this public $declared = 1;/** overload cannot is used in the attribute already defined */private $hidden = 2; /** The overload occurs only when this property 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 after version */Public function __isset ($name) {echo "is ' $name ' set?\n"; ReTurn isset ($this->data[$name]);              }/** PHP 5.1.0 version */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";            Var_dump (Isset ($obj->a));      unset ($obj->a);      Var_dump (Isset ($obj->a));      echo "\ n";            Echo $obj->declared. "\ n";            echo "Let's experiment with the private property named ' Hidden ': \ n";      echo "Privates is visible inside the class, so __get () is not used...\n";      echo $obj->gethidden (). "\ n";      echo "Privates not visible outside of class, so __get () is used...\n";      Echo $obj->hidden. "\ n";  

Property overloading: __set (), __get (), __isset (), __unset ()

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

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


11. Object Iteration


PHP5 provides the functionality of an iterative (iteration) object, just as with arrays, you can iterate through the properties of an object through foreach

    Class MyClass      {public          $var 1 = ' value 1 ';          Public $var 2 = ' value 2 ';          Public $var 3 = ' 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 strategy mode

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


Factory mode
Definition: Factory mode (Factory) allows you to instantiate an object while the code is executing. It is called the Factory mode because it is responsible for the "production" object. The parameter of the factory method is the class name of the object that you want to generate.

Factory mode Syntax:

    
 
      

Factory model Case:

    
 
   GetName ();            ? >  

Single case
Define three elements: 1, a class can have only one instance 2, you must create this instance 3 yourself, you must provide this instance to the system

Role: 1, if you need a class in the system to control some of the configuration information globally, then using the singleton mode can be easily implemented.
2, using singleton mode, can avoid a lot of new operation consumption resources ()
3 in a page request, easy to debug, because all the code in a class (such as database operation Class) can set hooks in the class, output the log, so as to avoid var_dump everywhere

Singleton mode (Singleton) is used to generate a unique object for a class. The most common place is the database connection. Once an object is generated using singleton mode, the object can be used by many other objects.
Single-piece mode is a design pattern we often use in development, using PHP5 object-oriented features, we can easily build a single-piece mode of application, the following is a single-piece mode in PHP implementation of several methods:

    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 instance of a class in a getinstance method.

A little modification of the example here can produce a generic method, just call any class that you want to use in 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, by calling the GetInstance method, you can produce an instance for any one 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 ();

With these three methods, we can easily apply a single-piece mode, which, if combined with Factory mode, will make our programming more organized and efficient.
---------------------------------------------------------------------------------------

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