search
HomeBackend DevelopmentPHP Tutorial第十节--抽象方法和抽象类 -- Classes and Objects in PHP5_PHP

/*
+-------------------------------------------------------------------------------+
| = 本文为Haohappy读>
| = 中Classes and Objects一章的笔记
| = 翻译为主+个人心得
| = 为避免可能发生的不必要的麻烦请勿转载,谢谢
| = 欢迎批评指正,希望和所有PHP爱好者共同进步!
| = PHP5研究中心: http://blog.csdn.net/haohappy2004
+-------------------------------------------------------------------------------+
*/

第十节--抽象方法和抽象类

面向对象程序通过类的分层结构构建起来. 在单重继承语言如PHP中, 类的继承是树状的. 一个根类有一个或更多的子类,再从每个子类继承出一个或更多下一级子类. 当然,可能存在多个根类,用来实现不同的功能. 在一个良好设计的体系中,每个根类都应该有一个有用的接口, 可以被应用代码所使用. 如果我们的应用代码被设计成与根类一起工作,那么它也可以和任何一个从根类继承出来的子类合作.

抽象方法是就像子类中一般的方法的占位符(占个地方但不起作用),它与一般方法不同—没有任何代码. 如果类中存在一个或更多抽象方法, 那么这个类就成了抽象类. 你不能实例化抽象类. 你必须继承它们,然后实例化子类. 你也可以把抽象类看成是子类的一个模板.

如果你覆写所有的抽象方法, 子类就变成一个普通的类. 如果没有覆写所有方法, 子类仍是抽象的. 如果一个类中中包含有抽象方法(哪怕只有一个), 你必须声明这个类是抽象的, 在class关键字前加上abstract.

声明抽象方法的语法与声明一般方法不同. 抽象方法的没有像一般方法那样包含在大括号{}中的主体部份,并用分号;来结束.

在例子6.13中, 我们定义了一个含有getArea方法的类Shape. 但由于不知道形状不可能确定图形的面积,确良我们声明了getArea方法为抽象方法. 你不能实例化一个Shape对象,但你可以继承它或在一个表达式中使用它, 就像例6.13中那样.

如果你建立了一个只有抽象方法的类,你就定义了一个接口(interface). 为了说明这种情况, PHP中有interface 和implements关键字. 你可以用interface来代替抽象类, 用implements来代替extends来说明你的类定义或使用一个接口. 例如, 你可以写一个myClass implements myIterface. 这两种方法可以依个人偏爱来选择.

/*注:
两种方法即指:
1. abstract class aaa{} (注意aaa中只有抽象方法,没有一般方法)
class bbb extends aaa{} (在bbb中覆写aaa中的抽象方法)
2. interface aaa{}
class bbb implements aaa{} (在bbb中覆写aaa中的抽象方法)
*/

Listing 6.13 Abstract classes

<?php 
   //abstract root class 抽象根类 
   abstract class Shape 
   { 
       abstract function getArea(); //定义一个抽象方法 
   } 

   //abstract child class 抽象子类 
   abstract class Polygon extends Shape //多边形 
   { 
       abstract function getNumberOfSides(); 
   } 

   //concrete class 实体类 三角形类 
   class Triangle extends Polygon 
   { 
       public $base; 
       public $height; 

       public function getArea() //覆写计算面积方法 
       { 
           return(($this->base * $this->height)/2); 
       } 

       public function getNumberOfSides() //覆写边数统计方法 
       { 
           return(3); 
       } 
   } 

   //concrete class 实体类四边形 
   class Rectangle extends Polygon 
   { 
       public $width; 
       public $height; 

       public function getArea() 
       { 
           return($this->width * $this->height); 
       } 

       public function getNumberOfSides() 
       { 
           return(4); 
       } 
   } 

   //concrete class 实体类 圆形 
   class Circle extends Shape 
   { 
       public $radius; 

       public function getArea() 
       { 
           return(pi() * $this->radius * $this->radius); 
       } 
   } 

   //concrete root class 定义一个颜色类 
   class Color 
   { 
       public $name; 
   } 

   $myCollection = array(); //建立形状的集合,放入数组 

   //make a rectangle 
   $r = new Rectangle; 
   $r->width = 5; 
   $r->height = 7; 
   $myCollection[] = $r; 
   unset($r); 

   //make a triangle 
   $t = new Triangle; 
   $t->base = 4; 
   $t->height = 5; 
   $myCollection[] = $t; 
   unset($t); 

   //make a circle 
   $c = new Circle; 
   $c->radius = 3; 
   $myCollection[] = $c; 
   unset($c); 

   //make a color 
   $c = new Color; 
   $c->name = "blue"; 
   $myCollection[] = $c; 
   unset($c); 

   foreach($myCollection as $s) 
   { 
       if($s instanceof Shape) //如果$s是Shape类的实例 
       { 
           print("Area: " . $s->getArea() . 
               "<br>\n"); 
       } 

       if($s instanceof Polygon) 
       { 
           print("Sides: " . 
               $s->getNumberOfSides() . 
               "<br>\n"); 
       } 

       if($s instanceof Color) 
       { 
           print("Color: $s->name<br>\n"); 
       } 

       print("<br>\n"); 
   } 

?> 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.