1
<?php

class MyClass
{
    public $prop1 = "I'm a class property!";

    public function __construct()
    {
        echo 'The class "', __CLASS__, '" was initiated!<br />';
    }

    public function __destruct()
    {
        echo 'The class "', __CLASS__, '" was destroyed.<br />';
    }

    public function __toString()
    {
        echo "Using the toString method: ";
        return $this->getProperty();
    }

    public function setProperty($newval)
    {
        $this->prop1 = $newval;
    }

    public function getProperty()
    {
        return $this->prop1 . "<br />";
    }
}

class MyOtherClass extends MyClass
{
    public function __construct()
    {
        parent::__construct(); // Call the parent class's constructor
        $this->newSubClass();
    }

    public function newSubClass()
    {
        echo "From a new subClass " . __CLASS__ . ".<br />";
    }
}

// Create a new object
$newobj = new MyOtherClass;


?>

Question:

If change $this->newSubClass(); to self::newSubClass();, it also works, so when I need to use $this->newSubClass();, and when need to use self::newSubClass();?

user2294256
  • 1,029
  • 1
  • 13
  • 22
  • 1
    self:: is use on static methods / $this is use on the obj itself. – David Strada Aug 21 '13 at 03:02
  • and `self` is almost never what you mean, usually you want to use `static`. See info on [late static binding](http://php.net/manual/en/language.oop5.late-static-bindings.php) – Orangepill Aug 21 '13 at 03:11

2 Answers2

3

Using self::methodName makes a static call to that method. You can't use $this, since you're not within an object's context.

Try this:

class Test
{
    public static function dontCallMeStatic ()
    {
         $this->willGiveYouAnError = true;
    }
}

Test::dontCallMeStatic();

You should get the following error:

Fatal error: Using $this when not in object context in...

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
1

From what I know if you use -> in $this->newSubClass(); it's used for accessing instance member of an object altough it can also access static member but such usage is discouraged.

then for this :: in self::newSubClass(); is usually used to access static members, but in general this symbol :: can be used for scope resolution and it may have either a class name, parent, self, or (in PHP 5.3) static to its left.

Niko Adrianus Yuwono
  • 11,012
  • 8
  • 42
  • 64