Created
March 16, 2012 06:42
-
-
Save varemenos/2048806 to your computer and use it in GitHub Desktop.
PHP - Sample Object
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 | |
// CONTINUE: | |
// CLASSES & OBJECTS - http://php.net/manual/en/language.oop5.php | |
// BASICS (TUTORIAL) - http://www.php.net/manual/en/language.oop5.basic.php | |
// CONSTRUCTORS - http://www.php.net/manual/en/language.oop5.decon.php | |
// new class | |
class Foo{ | |
// constructor | |
function __construct(){ | |
// set the initial value of the properly | |
$this->temp = 11; | |
echo '<br>Object Variables'; | |
var_dump(get_object_vars($this)); | |
echo '<br>Class Methods'; | |
var_dump(get_class_methods($this)); | |
} | |
// property | |
private $temp = 5; | |
// get method | |
public function getVar($name){ | |
if(isset($this->$name)){ | |
echo '<br>$' . $name . ' = ' . $this->$name; | |
}else{ | |
echo '<br>requested variable doesnt exist'; | |
} | |
} | |
// set method | |
public function setVar($name, $value){ | |
if(isset($this->$name)){ | |
$this->$name = $value; | |
}else{ | |
echo '<br>requested variable doesnt exist'; | |
} | |
} | |
} | |
class Bar extends Foo{ | |
// constructor | |
function __construct(){ | |
// call parent's constructor | |
parent::__construct(); | |
// this wont change the value of its parent | |
// but it will create another public variable | |
// $this->temp = 11; | |
// this wont change the value either | |
// $super->temp = 12; | |
} | |
} | |
// new object | |
$obj1 = new Foo(); | |
$obj2 = new Bar(); | |
// examples | |
$obj1->getVar('temp'); | |
$obj1->setVar('temp', 6); | |
$obj1->getVar('temp'); | |
echo '<br>'; | |
// examples | |
$obj2->getVar('temp'); | |
echo '<br>'; | |
// get created object's class | |
echo '<br>obj1 class = ' . get_class($obj1); | |
echo '<br>obj2 class = ' . get_class($obj2); | |
echo '<br>'; | |
// check if the created object is an instance of the created class | |
echo '<br>obj1 is instance of Foo : ' . ($obj1 instanceof Foo); | |
echo '<br>obj1 is instance of Bar : ' . ($obj1 instanceof Bar); | |
echo '<br>obj2 is instance of Foo : ' . ($obj2 instanceof Foo); | |
echo '<br>obj2 is instance of Bar : ' . ($obj2 instanceof Bar); | |
echo '<br><em>If object : 1, then its true</em>'; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment