OOP Programming with php
Object Oriented programming requires a different way of thinking how you construct your applications. Objects enable you to more closely model in code the real-world tasks, processes and ideas that your application is designed to handle. You can think of a class as a blueprint for constructing an object, you can build multiple instance of an object.
Lets start with creating a simple class example
Class begins with keyword Class and followed by a name that isn't reserved word in php. It contains the definition of methods, members and attributes of a class.
In test_demo.php, write following lines
Access this file in your favourite browser, output should be somethink like following :Lets start with creating a simple class example
Class begins with keyword Class and followed by a name that isn't reserved word in php. It contains the definition of methods, members and attributes of a class.
<?php
class demo{
private $_name;
public function __construct($name){
$this->_name = $name;
}
public function getName(){
return $this->_name;
}
public function setName($name){
$this->_name = $name;
}
public function __destruct(){
}
}
?>
The contructor to this object set class property 'name'. The accessor
method getname(), enable you to fetch the value of the private member
variable. Similarly, the setname() method enable you to assign a new
value to variable.In test_demo.php, write following lines
<?php
require_once('class_demo.php');
try {
$objdemo = new Demo('example1');
echo "Class name is : ". $objdemo->getName();
$objdemo->setName('Example2');
echo "Class new name is : " . $objdemo->getName();
} catch(Exception $e) {
echo "There was a problem :" . $e->getMessage();
}
?>
Class name is : example1
Class new name is : example2
Comments
Post a Comment