
声明一个类
|
171
}
class Person {
use Command, Marathon {
Command::run as runCommand;
Marathon::run insteadof Command;
}
}
$person = new Person;
$person->run();
$person->runCommand();
Running a marathonExecuting a command
抽象方法
PHP
还提供了一种机制,让一个类中特定的方法在子类中必须实现——在父类中这些方
法没有具体实现,仅提供方法名,这样你就可以提供一个抽象方法(
abstract method
)。
另外,一个类中只要有任何一种方法被定义为抽象方法,就要用
abstract
关键字将该类
定义为抽象类 :
abstract class Component {
abstract function printOutput();
}
class ImageComponent extends Component {
function printOutput() {
echo "Pretty picture";
}
}
抽象类不能被直接实例化,同时还要注意与其他语言不同,
PHP
不允许为抽象方法提供
一个默认的实现。
trait
也可以声明一个抽象方法,如果类中包含一个含有抽象方法的
trait
,则在这个类中
必须实现这个抽象方法
:
trait Sortable {
abstract function uniqueId(); ...