Created
January 21, 2016 04:07
-
-
Save mkormendy/6334b2e7b07c09160f06 to your computer and use it in GitHub Desktop.
When to use self over $this
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Person { | |
private $name; | |
public function __construct($name) { | |
$this->name = $name; | |
} | |
public function getName() { | |
return $this->name; | |
} | |
public function getTitle() { | |
return $this->getName()." the person"; | |
} | |
public function sayHello() { | |
echo "Hello, I'm ".$this->getTitle()."<br/>"; | |
} | |
public function sayGoodbye() { | |
echo "Goodbye from ".self::getTitle()."<br/>"; | |
} | |
} | |
class Geek extends Person { | |
public function __construct($name) { | |
parent::__construct($name); | |
} | |
public function getTitle() { | |
return $this->getName()." the geek"; | |
} | |
} | |
$geekObj = new Geek("Ludwig"); | |
$geekObj->sayHello(); | |
$geekObj->sayGoodbye(); | |
// outputs: | |
// Hello, I'm Ludwig the geek | |
// Goodbye from Ludwig the person | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment