Correct understanding of abstract class PHP applications

  For PHP programmers, the most difficult thing to grasp the number of PHP applications like this one abstract knowledge. In fact, as a novice to use yet to object-oriented programming knowledge, but later developed, using class interfaces using encapsulation or the like, the various modular program development, it is of course necessary.

  In natural language, we understand the abstract concept is a description of one kind of large objects, such description is for certain common characteristics for objects. So in PHP is the same, we have a class abstract, you can specify the general behavior of the class, the class should be a template, which indicates that the behavior of some of its sub-methods must be implemented.

PHP abstract class definitions apply:

abstract class ClassName{

}

PHP abstract class Application Notes:

  1. Define some methods, subclass must fully implement all the abstract methods
  2. You can not create an object from an abstract class, its significance is being extended
  3. abstract class typically have an abstract method, the method does not braces

Application examples PHP abstract class:

  abstract public function_name (); // Note no braces

  To demonstrate, let's implement a simple abstract class: calculate the area of ​​a rectangle. The rectangular shape can be extended from the class.

  1. < ?PHP   
  2. abstract class Shape {   
  3. abstract protected function get_area();   
  4. Different methods // and in general, this method does not braces   
  5. // You can not create an instance of an abstract class: $ Shape_Rect
     =  new new  the Shape ();   
  6. }   
  7. class Rectangle extends Shape{   
  8. private $width;   
  9. private $height;   
  10. function __construct($width=0,
    $height=0){   
  11. $this->width=$width;   
  12. $this->height=$height;   
  13. }   
  14. function get_area(){   
  15. echo ($this->width+$this->height)*2;   
  16. }   
  17. }   
  18. $Shape_Rect = new Rectangle(20,30);   
  19. $Shape_Rect->get_area();   
  20. ?>   

  This could be considered a simple example, basically illustrate the use of PHP in an abstract class, the other did not want to say. Personally I feel that the general abstract class in large project will use it, because I think the "rules" it is really too much to follow up, inconvenient to use! Of course this is just my opinion. Would also like to say something, PHP abstract class single application is inherited, which means you can only inherit from one class, but a class can not be inherited class A, class inheritance and B, if you want to achieve this function, too using the interface relevant knowledge, and knowledge are not discussed in this temporary PHP interface! Bottom line: single inheritance multi-interface!

Reproduced in: https: //www.cnblogs.com/in-loading/archive/2011/09/15/2178025.html

Guess you like

Origin blog.csdn.net/weixin_33811961/article/details/93700314