


PHP object-oriented programming (oop) study notes (1) - abstract classes, object interfaces, instanceof and contract programming_PHP tutorial
1. Abstract class in PHP
PHP 5 supports abstract classes and abstract methods. Classes defined as abstract cannot be instantiated. Any class must be declared abstract if at least one method in it is declared abstract. A method defined as abstract only declares its calling method (parameters) and cannot define its specific function implementation. A class can be declared abstract by using the abstract modifier in its declaration.
It can be understood that an abstract class serves as a base class and leaves specific details to successors. By abstracting concepts, you can create scalable architectures in your development projects.
abstract class AbstractClass
{
code...
}
1.1, Abstract method
Use the abstract keyword to define abstract methods. Abstract methods only retain the method prototype (the signature after the method body is removed from the method definition), which includes access levels, function keywords, function names and parameters. It does not contain ({}) or any code inside brackets. For example, the following code is an abstract method definition:
abstract public function prototypeName($protoParam);
When inheriting an abstract class, the subclass must define all abstract methods in the parent class; in addition, the access control of these methods must be the same (or more relaxed) as in the parent class. In addition, the method calling methods must match, that is, the type and number of required parameters must be consistent.
1.2. About abstract classes
A class must be declared as an abstract class as long as it contains at least one abstract method.
Methods declared as abstract must contain the same or lower access level when implemented.
Instances of abstract classes cannot be created using the new keyword.
Methods declared as abstract cannot contain function bodies.
If the extended class is also declared as an abstract class, you do not need to implement all abstract methods when extending the abstract class. (If a class inherits from an abstract class, it must also be declared abstract when it does not implement all abstract methods declared in the base class.)
1.3. Use abstract classes
abstract class Car
{
abstract function getMaxSpeend();
}
class Roadster extends Car
{
public $Speend;
public function SetSpeend($speend = 0)
{
$this->Speend = $speend;
}
public function getMaxSpeend()
{
return $this->Speend;
}
}
class Street
{
public $Cars ;
public $SpeendLimit ;
function __construct( $speendLimit = 200)
{
$this -> SpeendLimit = $speendLimit;
$this -> Cars = array();
}
protected function IsStreetLegal($car)
{
if ($car->getMaxSpeend() < $this -> SpeendLimit)
{
return true;
}
else
{
return false;
}
}
public function AddCar($car)
{
if($this->IsStreetLegal($car))
{
echo 'The Car was allowed on the road.';
$this->Cars[] = $car;
}
else
{
echo 'The Car is too fast and was not allowed on the road.';
}
}
}
$Porsche911 = new Roadster();
$Porsche911->SetSpeend(340);
$FuWaiStreet = new Street(80);
$FuWaiStreet->AddCar($Porsche911);
/**
*
* @result
*
* The Car is too fast and was not allowed on the road.[Finished in 0.1s]
*
*/
?>
2.对象接口
使用接口(interface),可以指定某个类必须实现哪些方法,但不需要定义这些方法的具体内容。
接口是通过 interface 关键字来定义的,就像定义一个标准的类一样,但其中定义所有的方法都是空的。
接口中定义的所有方法都必须是公有,这是接口的特性。
接口是一种类似于类的结构,可用于声明实现类所必须声明的方法。例如,接口通常用来声明API,而不用定义如何实现这个API。
大多数开发人员选择在接口名称前加上大写字母I作为前缀,以便在代码和生成的文档中将其与类区别开来。
2.1接口实现(implements)
要实现一个接口,使用 implements 操作符(继承抽象类需要使用 extends 关键字不同),类中必须实现接口中定义的所有方法,否则会报一个致命错误。类可以实现多个接口,用逗号来分隔多个接口的名称。
实现多个接口时,接口中的方法不能有重名。
接口也可以继承,通过使用 extends 操作符。
类要实现接口,必须使用和接口中所定义的方法完全一致的方式。否则会导致致命错误。
接口中也可以定义常量。接口常量和类常量的使用完全相同,但是不能被子类或子接口所覆盖。
2.2使用接口的案例
abstract class Car
{
abstract function SetSpeend($speend = 0);
}
interface ISpeendInfo
{
function GetMaxSpeend();
}
class Roadster extends Car implements ISpeendInfo
{
public $Speend;
public function SetSpeend($speend = 0)
{
$this->Speend = $speend;
}
public function getMaxSpeend()
{
return $this->Speend;
}
}
class Street
{
public $Cars ;
public $SpeendLimit ;
function __construct( $speendLimit = 200)
{
$this -> SpeendLimit = $speendLimit;
$this -> Cars = array();
}
protected function IsStreetLegal($car)
{
if ($car->getMaxSpeend() < $this -> SpeendLimit)
{
return true;
}
else
{
return false;
}
}
public function AddCar($car)
{
if($this->IsStreetLegal($car))
{
echo 'The Car was allowed on the road.';
$this->Cars[] = $car;
}
else
{
echo 'The Car is too fast and was not allowed on the road.';
}
}
}
$Porsche911 = new Roadster();
$Porsche911->SetSpeend(340);
$FuWaiStreet = new Street(80);
$FuWaiStreet->AddCar($Porsche911);
/**
*
* @result
*
* The Car is too fast and was not allowed on the road.[Finished in 0.1s]
*
*/
?>
3、类型运算符 instanceof
instanceof 运算符是 PHP5 中的一个比较操作符。他接受左右两边的参数,并返回一个boolean值。
确定一个 PHP 变量是否属于某个一类 CLASS 的实例
检查对象是不是从某个类型继承
检查对象是否属于某个类的实例
确定一个变量是不是实现了某个接口的对象的实例
echo $Porsche911 instanceof Car;
//result:1
echo $Porsche911 instanceof ISpeendInfo;
//result:1
4.Contract Programming
Design by Contract or Design by Contract (DbC) is a method of designing computer software. This method requires software designers to define formal, precise and verifiable interfaces for software components. In this way, a priori conditions, a posteriori conditions and invariants are added to traditional abstract data types. The "contract" or "contract" used in the name of this method is a metaphor because it is somewhat similar to the situation of a business contract.
A programming practice of implementing a declared interface before writing a class. This method is very useful in ensuring the encapsulation of classes. Using contract programming techniques, we can define the functionality of a view before creating an application, much like an architect draws a blueprint before building a building.
5.Summary
Abstract classes are classes declared using the abstract keyword. By marking a class as abstract, we can defer implementation of the declared methods. To declare a method as abstract, simply remove the method entity containing all curly braces and end the line of code where the method is declared with a semicolon.
Abstract classes cannot be instantiated directly, they must be inherited.
If a class inherits from an abstract class, it must also be declared abstract when it does not implement all abstract methods declared in the base class.
In an interface, we can declare a method prototype without a method body, which is very similar to an abstract class. The difference between them is that interfaces cannot declare any methods with method bodies; and the syntax they use is also different. In order to force uncovering rules on a class, we need to use the implements keyword instead of the extends keyword.
In some cases we need to determine whether a class is a type of a specific class, or whether it implements a specific interface. instanceof is suitable for this task. instanceof checks three things: whether the instance is of a specific type, whether the instance inherits from a specific type, and whether the instance or any of its ancestor classes implement a class-specific interface.
Some languages have the ability to inherit from multiple classes, this is called multiple inheritance. PHP does not support multiple inheritance. The idea is that it provides the function of declaring multiple interfaces for a class.
Interfaces are useful for declaring rules that a class must follow. Contractual programming technology uses this feature to enhance encapsulation and optimize workflow.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Golang has no abstract classes. Golang is not an object-oriented (OOP) language. It has no concepts of classes, inheritance, and abstract classes. However, there are structures (structs) and interfaces (interfaces) in golang, which can be indirectly implemented through the combination of struct and interface. Abstract classes in object languages.

The function of instanceof is to determine whether an object is an instance of a certain class, or whether it implements a certain interface. instanceof is an operator used to check whether an object is of a specified type. Usage scenarios of instanceof operator: 1. Type checking: can be used to determine the specific type of an object, so as to perform different logic according to different types; 2. Interface judgment: can be used to determine whether an object implements an interface, so as to determine whether an object implements an interface. The definition of the interface calls the corresponding method; 3. Downward transformation, etc.

Interfaces and abstract classes are used in design patterns for decoupling and extensibility. Interfaces define method signatures, abstract classes provide partial implementation, and subclasses must implement unimplemented methods. In the strategy pattern, the interface is used to define the algorithm, and the abstract class or concrete class provides the implementation, allowing dynamic switching of algorithms. In the observer pattern, interfaces are used to define observer behavior, and abstract or concrete classes are used to subscribe and publish notifications. In the adapter pattern, interfaces are used to adapt existing classes. Abstract classes or concrete classes can implement compatible interfaces, allowing interaction with original code.

Java allows inner classes to be defined within interfaces and abstract classes, providing flexibility for code reuse and modularization. Inner classes in interfaces can implement specific functions, while inner classes in abstract classes can define general functions, and subclasses provide concrete implementations.

Both functional interfaces and abstract classes are used for code reusability, but they are implemented in different ways: functional interfaces through reference functions, abstract classes through inheritance. Functional interfaces cannot be instantiated, but abstract classes can. Functional interfaces must implement all declared methods, while abstract classes can only implement some methods.

Interface Interface defines abstract methods and constants in Java. The methods in the interface are not implemented, but are provided by the class that implements the interface. The interface defines a contract that requires the implementation class to provide specified method implementations. Declare the interface: publicinterfaceExampleInterface{voiddoSomething();intgetSomething();} Abstract class An abstract class is a class that cannot be instantiated. It contains a mixture of abstract and non-abstract methods. Similar to interfaces, abstract methods in abstract classes are implemented by subclasses. However, abstract classes can also contain concrete methods, which provide default implementations. Declare abstract class: publicabstractcl

Interfaces and abstract classes are used to create extensible PHP code, and there is the following key difference between them: Interfaces enforce through implementation, while abstract classes enforce through inheritance. Interfaces cannot contain concrete methods, while abstract classes can. A class can implement multiple interfaces, but can only inherit from one abstract class. Interfaces cannot be instantiated, but abstract classes can.

Interface: An implementationless contract interface defines a set of method signatures in Java but does not provide any concrete implementation. It acts as a contract that forces classes that implement the interface to implement its specified methods. The methods in the interface are abstract methods and have no method body. Code example: publicinterfaceAnimal{voideat();voidsleep();} Abstract class: Partially implemented blueprint An abstract class is a parent class that provides a partial implementation that can be inherited by its subclasses. Unlike interfaces, abstract classes can contain concrete implementations and abstract methods. Abstract methods are declared with the abstract keyword and must be overridden by subclasses. Code example: publicabstractcla
