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

时间:2011-07-28 12:16:29

标签: php

  

可能重复:
  PHP: self vs. $this

来自php手册,请让我知道我使用自我关键字的地点和原因

<?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";
?> 

2 个答案:

答案 0 :(得分:3)

self允许你引用你现在所在的班级;它就像$ this,但不是关于实例,但是允许你在没有命名类的情况下调用静态方法(父类以类似的方式工作,但是指向父类,而不是自我类 - 我认为是不言自明的。)

答案 1 :(得分:2)

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

相关问题