OOPS concepts in PHP with real-time examples
Object-Oriented programming requires a different way of thinking about 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 instances of an object.
Let's start with creating a simple class example
Class begins with keyword Class and is followed by a name that isn't a 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(){
}
}
?>In test_demo.php, write the 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();
}
?>
The class name is: example1
The class new name is: example2


Post A Comment:
0 comments: