varemenos
3/16/2012 - 6:42 AM

PHP - Sample Object

PHP - Sample Object

<?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>';
?>