Possible Duplicate:
PHP: self vs. $this
it is from php manual, please let me know where and why i use self keyword
<?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-开发者_如何学Go>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";
?>
self allows you to refer to class in which you currently are; it's like $this, but not about instance, but allows you to call static methods without naming the class (parent works in a similar manner, but points to parent class, not self class - self-explanatory, I think).
self is used to access class methods and variables (static ones) while $this is for accessing object instance variables and methods.
精彩评论