Last active
August 29, 2015 14:05
-
-
Save harisrozak/f2facf0c20d0e6f8310e to your computer and use it in GitHub Desktop.
PHP :: Sample OOP Style
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 | |
/** | |
* PHP OOP sample | |
* Tutorial here: http://code.tutsplus.com/tutorials/object-oriented-php-for-beginners--net-12762 | |
*/ | |
class MyClass | |
{ | |
public $variable; | |
public static $static_variable; | |
public function __construct() | |
{ | |
echo 'The '.__CLASS__.' is activated!'; | |
$this->variable = "variable value from class MyClass"; | |
self::$static_variable = 'i am a new static variable'; | |
} | |
public function get_variable() | |
{ | |
echo $this->variable; | |
} | |
public function set_variable($value) | |
{ | |
$this->variable = $value; | |
} | |
public static function get_static_variable() | |
{ | |
echo self::$static_variable . ' [updated]'; | |
} | |
} | |
class OtherClass extends MyClass | |
{ | |
public function __construct() | |
{ | |
parent::__construct(); | |
echo '<br />'; | |
echo 'The '.__CLASS__.' is activated!'; | |
} | |
} | |
// init new class and run the __construct method inside it | |
$obj = new MyClass; | |
echo '<br />'; | |
// set variable | |
$obj->set_variable('sublime text'); | |
echo '<br />'; | |
// get variable | |
$obj->get_variable(); | |
echo '<br />'; | |
// direct get variable from initiated class | |
echo $obj->variable; | |
echo '<br />'; | |
// direct get static variable | |
echo MyClass::$static_variable; | |
echo '<br />'; | |
// get static variable from a static function | |
MyClass::get_static_variable(); | |
echo '<br />'; | |
// init OtherClass that extends the MyClass | |
$other_obj = new OtherClass; | |
echo '<br />'; | |
// get variable from the extended class (MyClass) | |
$other_obj->get_variable(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment