声明类成员或方法为static,就可以不实例化类而直接访问。不能通过一个对象访问其中的静态成员(静态方法除外)
由于静态方法不需要通过对象即可调用,所以伪变量$this在静态方法中不可用。
静态属性不可以由对象通过->操作符来访问。
Example #1 静态成员代码示例
<?php
class Foo
{
public static $my_static = 'foo';
public function staticValue() {
return self::$my_static;
}
}
class Bar extends Foo
{
public function fooStatic() {
return parent::$my_static;
}
}
print Foo::$my_static . "
";
$foo = new Foo();
print $foo->staticValue() . "
";
print $foo->my_static . "
"; // Undefined "Property" my_static
print $foo::$my_static . "
";
$classname = 'Foo';
print $classname::$my_static . "
"; // PHP 5.3.0之后可以动态调用
print Bar::$my_static . "
";
$bar = new Bar();
print $bar->fooStatic() . "
";
?>
Example #2 静态方法代码示例
<?php
class Foo {
public static function aStaticMethod() {
// ...
}
}
Foo::aStaticMethod();
$classname = 'Foo';
$classname::aStaticMethod(); // As of PHP 5.3.0
?>
浙公网安备 33010602011771号