开发者

what is the function of self keyword in php [duplicate]

开发者 https://www.devze.com 2023-03-23 18:27 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: PHP: self vs. $this it is from php manual, please let me know where and why i use self keyword
This question already has answers here: Closed 11 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消