-1

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->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";
?> 
Community
  • 1
  • 1
php.khan
  • 1,224
  • 1
  • 12
  • 21
  • my_static is a static var. you can access it from outside the class via `::$my_static` (`FOO::$my_static`) to access it from within the class you use `self`. `self` is basicly the same as `$this`, but `$this` only works if you initiate the class (`new FOO()`) – Rufinus Jul 28 '11 at 12:21

2 Answers2

3

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).

Griwes
  • 8,805
  • 2
  • 43
  • 70
2

self is used to access class methods and variables (static ones) while $this is for accessing object instance variables and methods.

Diabl0
  • 146
  • 7