Skip to content

Instantly share code, notes, and snippets.

@mkormendy
Created January 21, 2016 04:07
Show Gist options
  • Save mkormendy/6334b2e7b07c09160f06 to your computer and use it in GitHub Desktop.
Save mkormendy/6334b2e7b07c09160f06 to your computer and use it in GitHub Desktop.
When to use self over $this
<?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