php中self关键字的功能是什么


what is the function of self keyword in php

可能重复:
PHP:自我vs.$this

它来自php手册,请让我知道我在哪里以及为什么使用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->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允许您引用当前所在的类;它与$this类似,但与实例无关,但允许您在不命名类的情况下调用静态方法(parent以类似的方式工作,但指向parent类,而不是self-class——我认为这是不言自明的(。

self用于访问类方法和变量(静态方法和变量(,$this用于访问对象实例变量和方法。