Skip to content

Instantly share code, notes, and snippets.

@solocommand
Created March 21, 2014 01:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save solocommand/9677633 to your computer and use it in GitHub Desktop.
Save solocommand/9677633 to your computer and use it in GitHub Desktop.
PHP OOP Quick How-To
<?php
class MyTestClass
{
private $privateVar = array();
protected $protectedVar;
public $publicVar;
public static $staticVar = 'boom.';
/**
* This "magic" method is run when a object of this type is instantiated.
* @param $privateVar variable that can be injected on construct to bypass private accessor. Defau
*/
__construct(array $privateVar = null)
{
// Only set $privateVar if it is set on construct.
if (!is_null($privateVar)) {
$this->privateVar = $privateVar;
}
$this->runsAfterInit(4);
}
/**
* This method cannot be changed in extended classes because it is final.
* It can only be accessed from this instance of MyTestClass because it is private.
* It will be called when this class is constructed.
*/
final private function runsAfterInit(int $number)
{
echo __METHOD__."\r\n";
}
protected function getClassVariables()
{
return array($this->privateVar, $this->protectedVar, $this->publicVar);
}
public function getPublicVar()
{
return $this->publicVar;
}
public function getPrivateVar()
{
return $this->privateVar;
}
public function getProtectedVar()
{
return $this->protectedVar();
}
public function setPrivateVar($privateVar)
{
$this->privateVar = $privateVar;
return $this;
}
public static setStaticVar($staticVar)
{
self::$staticVar = $staticVar;
}
}
class MyExtendedTestClass extends MyTestClass
{
private $privateVar = 'extended';
protected function getClassVariables()
{
return array($this->privateVar, $this->protectedVar, $this->publicVar);
}
}
$testClass = new MyTestClass();
// Prints array()
print_r($testClass->getPrivateVar());
$extendedTestClass = new MyExtendedTestClass();
// Prints 'extended'
print_r($extendedTestClass->getPrivateVar());
$testClass->setPrivateVar('Test');
// Prints 'extended'
print_r($extendedTestClass->getPrivateVar());
// Prints 'boom.'
print_r(MyTestClass::getStaticVar());
MyTestClass::setStaticVar('statiiic');
// Prints 'statiiic'
print_r(MyExtendedTestClass::getStaticVar());
// Never use closing php tags. Causes crazy headaches with header output and such.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment