zl程序教程

您现在的位置是:首页 >  其他

当前栏目

PHP 子类重写父类成员详解 overwrite

2023-03-07 09:01:47 时间

1. 重写规则


一、重写的类成员访问权限不能低于父类

二、 重写的类成员是不是静态成员必须和父类保持一致

三、重写方法时,参数类型必须保持一致,参数数量可多不可少,默认值可多不可少

2. 重写的类成员访问权限不能低于父类


致命错误:用户::$name的访问级别必须是public(如在class Base中),位于E:\www\1.php的第15行

Fatal error: Access level to User::$name must be public (as in class Base) in E:\www\1.php on line 15
class Base

3. 重写的类成员是不是静态成员必须和父类保持一致


致命错误:无法在E:\www\1.php的第15行将非静态属性 name重新声明为静态属性 name

Fatal error: Cannot redeclare non static Base::$name as static User::$name in E:\www\1.php on line 15
class Base

4. 方法参数类型必须保持一致


警告:User::main(intid)的声明应与E:\www\1.php第14行中的Base::main(stringid)兼容

Warning: Declaration of User::main(int $id) should be compatible with Base::main(string $id) in E:\www\1.php on line 14
class Base

5. 方法参数数量大于父类方法参数数量时, 参数必须有默认值


警告:User::main(intid,stringname)的声明应与E:\www\1.php第16行中的Base::main(int

Warning: Declaration of User::main(int $id, string $name) should be compatible with Base::main(int $id) in E:\www\1.php on line 16
class Base

6. 父类方法参数有默认值时, 子类方法必须也有默认值


警告:User::main(stringname)的声明应与E:\www\1.php第15行中的Base::main(stringname=’’)兼容

Warning: Declaration of User::main(string $name) should be compatible with Base::main(string $name = '') in E:\www\1.php on line 15
class Base