Class/Object Functions

PHP has many inbuilt functions to help with your programming needs. Here's an example script with a few to be getting on with:

	class Person {
		public $name = "Superman";
		public $age = "99";

		public function __construct($myName, $myAge){
			$this->name = $myName;
			$this->age = $myAge;
		public function greet(){
			echo "$this->name says hi!";
	echo "Create an object instance, calling its constructor to set the name.<br><br>";
	$spidey = new Person("Peter Parker", 42);

	echo "echo the name property: <br>";
	echo "$spidey->name <br><br>";

	echo "Return a boolean if the class exists or not: " . class_exists("Person") . "<br><br>"; //returns boolean

	echo "echo the methods within the class:<br>";
	$myClassMethods = get_class_methods('Person'); //returns array of class methods
	foreach($myClassMethods as $methodName){
		echo $methodName . "<br>";
	echo "<br>";

	echo "echo the properties within the class:<br>";
	$myClassProperties = get_class_vars('Person');//returns an associative array of class properties
	foreach($myClassProperties as $propertyName => $value){
		echo "$propertyName = $value<br>";
	echo "<br>";

	echo "\$spidey was created using the " . get_class($spidey) . " class<br><br>";

	echo "Display an array of the names of the declared classes in the script<br>";
	echo "Depending on what extensions you have compiled or loaded into PHP, additional classes could be present!<br>";
	echo "<br><br>";

	echo "<pre>" . var_export($spidey, TRUE) . "</pre>" ;

Leave a Reply