PHP 面向对象基础:参数类型约束 1 个改进

PHP 5 可以使用类型约束。函数的参数可以指定必须为对象(在函数原型里面指定类的名字)。如果一个类或接口指定了类型约束,则其所有的子类或实现也都如此。

class Parents {}

实现 Parents

class Son extends Parents { public function read() { echo 'Son is reading.' . '<br />'; } public function write() { echo 'Son is writing.' . '<br />'; } } class Daugthter extends Parents { public function read() { echo 'Daugthter is reading.' . '<br />'; } public function write() { echo 'Daugthter is writing.' . '<br />'; } }

类型约束示例

class Doing { /** * Son 对象约束 * @param Son $son */ public function sonRead(Son $son) { $son->read(); } /** * Daughter 对象约束 * @param Daugthter $daugthter */ public function daugtherRead(Daugthter $daugthter) { $daugthter->read(); } /** * Parents 对象约束 * @param Parents $parents */ public function parentsWrite(Parents $parents) { $parents->write(); } } $doing = new Doing(); $doing->sonRead(new Son()); // Son is reading. $doing->daugtherRead(new Daugthter()); // Daugthter is reading. $doing->parentsWrite(new Son()); // Son is writing. $doing->parentsWrite(new Daugthter()); // Daugthter is writing.

类型约束也能使用在函数里

function doing (Son $son) { $son->read(); } doing(new Son()); // Son is reading.

类型约束允许 null

function test(Son $obj = null) { echo 'Nothing here.' . '<br />'; } test(null); // Nothing here.

函数调用的参数与定义的参数类型不一致时会抛出致命错误

// Fatal error: Uncaught TypeError: Argument 1 passed to Doing::sonRead() must be an instance of Son, instance of Daugthter given $doing->sonRead(new Daugthter());
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!