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();?

2
  • 1
    self:: is use on static methods / $this is use on the obj itself. Commented Aug 21, 2013 at 3:02
  • and self is almost never what you mean, usually you want to use static. See info on late static binding Commented Aug 21, 2013 at 3:11

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.