PHP 类抽象
phpserver side programmingprogramming更新于 2025/7/19 1:07:17
简介
在面向对象编程中,抽象类是可以实例化的类,也就是说,无法声明此类的对象。PHP 从 5.0 版本开始支持抽象类的概念。
使用 abstract 关键字定义的类将成为抽象类。此外,任何包含至少一个抽象方法的类也被视为抽象类。
语法
<?php
class testclass{
//
}
?>
如果我们尝试创建此类的对象,PHP 解析将引发如下错误 −
$a=new testclass(); PHP Fatal error: Uncaught Error: Cannot instantiate abstract class testclass
抽象方法
抽象方法仅声明其签名,即其可见性、参数和返回类型(带有类型提示),不具备任何功能。继承此类抽象类的类必须重写(提供定义)所有抽象方法。子类中相应的方法必须与父类具有相同的签名。如果子类不满足此条件,PHP 解析器将抛出异常。扩展抽象类的类现在可以被实例化,因此它被称为具体类
在以下示例中,父类有两个抽象方法,但子类中仅重新定义了其中一个。这将导致如下错误 −
示例
<?php
abstract class testclass{
abstract function test1();
abstract function hello();
}
class myclass extends testclass{
function test1(){
echo "Overrides parent test method";
}
}
$a=new myclass();
?>
输出
以下是错误信息
PHP Fatal error: Class myclass contains 1 abstract method and must therefore be declared abstract or implement the remaining methods (testclass::hello)
带参数的抽象方法
当抽象方法定义时带有参数,则必须在子类中用相同数量的参数重写它
在以下示例中,父类中的抽象方法有两个参数。子类也定义了带有两个参数的相同函数
示例
<?php
abstract class testclass{
abstract function hello($name, $age);
}
class myclass extends testclass{
function hello($name, $age){
echo "My name is $name and my age is $age";
}
}
$a=new myclass();
$a->hello("Ravi",20);
?>
输出
这将产生以下输出−
My name is Ravi and my age is 20

