search
HomeBackend DevelopmentPHP TutorialExploration of PHP5.0 Object Model: Abstract Methods and Abstract Classes_PHP Tutorial

Exploration of PHP5.0 Object Model: Abstract Methods and Abstract Classes_PHP Tutorial

Jul 21, 2016 pm 04:11 PM
layeredandexistobjectabstractexploremethodConstructModelofprogramkindstructurepassFor

Object-oriented programs are built through a hierarchical structure of classes. In single inheritance languages ​​such as PHP, class inheritance is tree-like. A root class has one or more subclasses, and then one or more subclasses are inherited from each subclass. More next-level subcategories. Of course, there may be multiple root classes used to implement different functions. In a well-designed system, each root class should have a useful interface that can be used by application code. If our application code is designed to work with the root class, it can also work with any subclass that inherits from the root class.

An abstract method is a placeholder just like a normal method in a subclass (it takes up a place but does not work). It is different from a normal method - it does not have any code. If there are one or more abstract methods in a class, then the class becomes an abstract class. You cannot instantiate abstract classes. You must inherit from them and then instantiate subclasses. You can also think of abstract classes as a template for subclasses.

If you override all abstract methods, the subclass becomes a normal class. If all methods are not overridden, the subclass is still abstract. If a class contains an abstract method (even if there is only one), you must declare the class to be abstract by adding abstract before the class keyword.

The syntax of declaring an abstract method is different from that of declaring a general method. The abstract method does not have a main body contained in braces {} like a general method, and ends with a semicolon;.

In Example 6.13, we define a class Shape that contains a getArea method. But since it is impossible to determine the area of ​​the figure without knowing the shape, we declared the getArea method as an abstract method. You cannot instantiate a Shape object, but you can inherit from it or use it in an expression, as in Example 6.13.

If you create a class with only abstract methods, you define an interface. To illustrate this situation, PHP has the interface and implements keywords. You can use interface instead of abstract classes and implements instead of extends to describe your class definition or use an interface. For example, you can write a myClass implements myIterface. You can choose between these two methods according to personal preference.

/*Note:
The two methods refer to:
1. abstract class aaa{} (note that there are only abstract methods in aaa, no general methods)
class bbb extends aaa{} (in bbb Override the abstract method in aaa in bbb)
2. interface aaa{}
class bbb implements aaa{} (overwrite the abstract method in aaa in bbb)
*/

Listing 6.13 Abstract classes

//abstract root class abstract root class
abstract class Shape
{
abstract function getArea(); //Define an abstract method
}

//abstract child class abstract subclass
abstract class Polygon extends Shape //Polygon
{
abstract function getNumberOfSides();
}

//concrete class entity class triangle class
class Triangle extends Polygon
{
public $base;
public $height;

Public function getArea() //Override the area calculation method
{
return(($this->base * $this->height)/2);
}

public function getNumberOfSides() //Override the side counting method
{
return(3);
}
}

//concrete class entity class quadrilateral
class Rectangle extends Polygon
{
public $width;
public $height;

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

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

//concrete class entity class circle
class Circle extends Shape
{
public $radius;

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

//concrete root class defines a color class
class Color
{
public $name;
}

$myCollection = array(); //Create a collection of shapes and put it into the 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) //If $s is an instance of Shape class
{
print("Area: " . $ s->getArea() . "n");
 }

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

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

print("n");
}

?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/313902.htmlTechArticleObject-oriented programs are built through the hierarchical structure of classes. In single inheritance languages ​​such as PHP, class inheritance It is tree-like. A root class has one or more subclasses, and inherits from each subclass...
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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools