Creating Constructors with Classes in PHP
<?php class student { var $name; var $age; var $grade; function student($n,$a,$g) { $this->name=$n; $this->age=$a; $this->grade=$g; } function display_info() { echo("<p>Name : $this->name"); echo("<p>Age : $this->age"); echo("<p>Grade : $this->grade"); } } $sobj = new student("Item Raja","15","A"); echo("<center><h2>Displaying Student Information</h2></center>"); echo("<font size=4>"); $sobj->display_info(); echo("</font>"); ?>
Example process of creating classes and objects in PHP
<?php class emp { var $name; var $address; var $dept; function assign_info($n,$a,$d) { $this->name=$n; $this->state=$a; $this->dept=$d; } function display_info() { echo("<p>Employee Name : $this->name"); echo("<p>State : $this->state"); echo("<p>Department : $this->dept"); } } $empobj = new emp; $empobj->assign_info("kaka lname","California","Accounts"); echo("<center><h2>Displaying Employee Information</h2></center>"); echo("<font size=4>"); $empobj->display_info(); echo("</font>"); ?>
Defining an object destructor in PHP
A destructor is a method that is called when an object is destroyed. An example use of destructor is to save information from a database into an object when it’s deleted. A destructor is defined as a method named __destruct( )
Example in PHP5:
<?php class person { public $username; function __construct($username, $password) { if ($this->validate_user($username, $password)) { $this->username = $username; } } function get_fullname($username) { // load profile from database } function __destruct() { db_close($this->handle); // close the database connection } } $user = new user('mani', 'kaka'); // using built-in constructor ?>
Destructors are not available in PHP4.
Deleting an object in PHP
Objects are automatically destroyed when a PHP script ends. To force the destruction of an object or to explicitly free the memory used by an object, we can use the unset() php function.
Example in PHP5:
<?php class person { public $username; function __construct($username, $password) { if ($this->validate_user($username, $password)) { $this->username = $username; } } function get_fullname($username) { // load profile from database } } $user = new user('mani', 'kaka'); // using built-in constructor unset($user); ?>
Defining an object constructor in PHP
The method named __construct() (two underscores) acts as a constructor. Constuctor is a method that is called when an object is instantiated without having to explicitly invoke it.
Example in PHP5:
<?php class person { public $username; function __construct($username, $password) { if ($this->validate_user($username, $password)) { $this->username = $username; } } function get_fullname($username) { // load profile from database } } $user = new user('mani', 'kaka'); // using built-in constructor $user->get_fullname($_GET['username']); ?>
Example in PHP4:
In php4, the constuctor has the same name as the class.
<?php class person { public $username; function person($username, $password) { if ($this->validate_user($username, $password)) { $this->username = $username; } } function get_fullname($username) { // load profile from database } } $user = new user('mani', 'kaka'); // using built-in constructor $user->get_fullname($_GET['username']); ?>
Create a new instance of an object in PHP
Instantiating objects is simple. Define the class, then use new to create an instance of the class.
Example:
<?php class person { function get_fullname($username) { // load profile from database } } $user = new person; $user->get_fullname($_GET['username']); ?>
Using Default Constructors
<?php class Dog { function __construct($name='No-name', $breed='breed unknown', $price = 15) { $this->name = $name; $this->breed = $breed; $this->price = $price; } } $aDog = new Dog(); $tweety = new Dog('A', 'a'); printf("<p>%s is a %s and costs \$%.2f.</p>\n", $aDog->name, $aDog->breed, $aDog->price); $tweety->price = 24.95; printf("<p>%s is a %s and costs \$%.2f.</p>\n", $tweety->name, $tweety->breed, $tweety->price); ?>
Using Inheritance To Efficiently Represent Various Vehicle Types
<? class Vehicle { var $model; var $current_speed; function setSpeed($mph) { $this->current_speed = $mph; } function getSpeed() { return $this->current_speed; } }class Auto extends Vehicle { var $fuel_type; function setFuelType($fuel) { $this->fuel_type = $fuel; } function getFuelType() { return $this->fuel_type; }}class Airplane extends Vehicle { var $wingspan; function setWingSpan($wingspan) { $this->wingspan = $wingspan; } function getWingSpan() { return $this->wingspan; } } ?>
Using Private And Public In Classes
<?php class myPHP5Class { private $my_variable; public function my_method($param) { echo "my_method($param)!\n"; echo "my variable is: "; echo "{$this->my_variable}\n"; } } $myobject = new myPHP5Class(); $myobject->my_method("MyParam"); $myobject->my_variable = 10; ?>
Using __Sleep() And __Wakeup() For Objects
<?php class UserClass { public $sessionID; public $username; public function __sleep() { session_destroy(); return array("username"); } public function __wakeup() { session_start(); $this->sessionId = session_id(); } } session_start(); $user = new UserClass; $user->sessionId = session_id(); $seralized_user = serialize($user); unset($user); $user = unserialize($serialized_user); ?>
Using Static Methods And Properties To Limit Instances Of A Class (Php 5 Only)
<?phpclass Shop { private static $instance; public $name="shop"; private function ___construct() { } public static function getInstance() { if ( empty( self::$instance ) ) { self::$instance = new Shop(); } return self::$instance; } }$first = Shop::getInstance(); $first-> name="A";$second = Shop::getInstance(); print $second -> name; ?>
Using The -> And :: Operators To Call Hypnotize
<?php class Cat { }class MyCat extends Cat { function MyCat( ) { } public static function hypnotize( ) { echo ("The cat was hypnotized."); return; } }MyCat::hypnotize( );$h_cat = new MyCat( ); $h_cat->hypnotize( );
Using The __Autoload() Function
<?php function __autoload($class) { $files = array('MyClass' => "/path/to/myClass.class.php", 'anotherClass' => "/path/to/anotherClass.class.php"); if(!isset($files[$class])) return; require_once($files[$class]); } $a = new MyClass; $b = new anotherClass; ?>
Using The __Call() Method
<?php class ParentClass { function __call($method, $params) { echo "The method $method doesn't exist!\n"; } } class ChildClass extends ParentClass { function myFunction() { } } $inst = new ChildClass(); $inst->nonExistentFunction(); ?>
Using The __Clone() Method
<?php class myObject { public $var_one = 10; public $var_two = 20; function __clone() { $this->var_two = 0; } } $inst_one = new myObject(); $inst_two = clone $inst_one; var_dump($inst_one); var_dump($inst_two); ?>
Using The Clone Statement
<?php class Integer { private $number; public function getInt() { return (int)$this->number; } public function setInt($num) { $this->number = (int)$num; } } $class_one = new Integer(); $class_one_copy = clone $class_one; ?>
Using The Extends Keyword To Define A Subclass
<?php class Cat { var $age; function Cat($new_age){ $this->age = $new_age; } function Birthday( ){ $this->age++; } } class MyCat extends Cat { function MyCat( ) { } function sleep( ) { echo("Zzzzzz.<br />"); } } $fluffy=new MyCat( ); $fluffy->Birthday( ); $fluffy->sleep( ); echo "Age is $fluffy->age <br />"; ?>
Using The Parent Construct
<?php class Cat { var $age; function Cat($new_age){ $this->age = $new_age; } function Birthday( ){ $this->age++; } function Eat( ){ echo "Chomp chomp."; } function Meow( ){ echo "Meow."; } }class MyCat extends Cat { function MyCat( ) { } function eat( ) { parent::eat( ); $this->meow( ); } } ?>
Using The Php 5 Style Constructor
<?php class Cat { Function __constructor( ){ } } ?>
Using The __Tostring() Method
<?php class User { private $username; function __construct($name) { $this->username = $name; } public function getUserName() { return $this->username; } function __toString() { return $this->getUserName(); } } $user = new User("john"); echo $user; ?>
