【发布时间】:2011-10-15 02:05:49
【问题描述】:
可能重复:
PHP: self vs. $this
它来自 php 手册,请告诉我我在哪里以及为什么使用 self 关键字
<?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 . "\n";
$foo = new Foo();
print $foo->staticValue() . "\n";
print $foo->my_static . "\n"; // Undefined "Property" my_static
print $foo::$my_static . "\n";
$classname = 'Foo';
print $classname::$my_static . "\n"; // As of PHP 5.3.0
print Bar::$my_static . "\n";
$bar = new Bar();
print $bar->fooStatic() . "\n";
?>
【问题讨论】:
-
my_static 是一个静态变量。您可以通过
<CLASSNAME>::$my_static(FOO::$my_static) 从课堂外访问它,也可以在您使用self的课堂内访问它。self与$this基本相同,但$this仅在您启动课程时有效(new FOO())
标签: php