这是PHP的已知“怪癖”。 这是设计使然,以防止向后传播,以便弄清楚一段时间之前我们是否实际实例化了一个对象(请记住,PHP是解释的,不是编译的)。 但是,如果未实例化对象,则通过via范围解析运算符访问任何非静态成员将发出致命错误。
由PHP.net提供:class User {
const GIVEN = 1; // class constants can't be labeled static nor assigned visibility
public $a=2;
public static $b=3;
public function me(){
echo "print me";
}
public static function you() {
echo "print you";
}
}
class myUser extends User {
}
// Are properties and methods instantiated to an object of a class, & are they accessible?
//$object1= new User(); // uncomment this line with each of the following lines individually
//echo $object1->GIVEN . ""; // yields nothing
//echo $object1->GIVE . ""; // deliberately misnamed, still yields nothing
//echo $object1->User::GIVEN . ""; // yields nothing
//echo $object1->a . ""; // yields 2
//echo $object1->b . ""; // yields nothing
//echo $object1->me() . ""; // yields print me
//echo $object1->you() . ""; // yields print you
// Are properties and methods instantiated to an object of a child class, & are accessible?
//$object2= new myUser(); // uncomment this line with each of the following lines individually
//echo $object2->GIVEN . ""; // yields nothing
//echo $object2->a . ""; // yields 2
//echo $object2->b . ""; // yields nothing
//echo $object2->me() . ""; // yields print me
//echo $object2->you() . ""; // yields print you
// Are the properties and methods accessible directly in the class?
//echo User::GIVEN . ""; // yields 1
//echo User::$a . ""; // yields fatal error since it is not static
//echo User::$b . ""; // yields 3
//echo User::me() . ""; // yields print me
//echo User::you() . ""; // yields print you
// Are the properties and methods copied to the child class and are they accessible?
//echo myUser::GIVEN . ""; // yields 1
//echo myUser::$a . ""; // yields fatal error since it is not static
//echo myUser::$b . ""; // yields 3
//echo myUser::me() . ""; // yields print me
//echo myUser::you() . ""; // yields print you
?>