PHP

oops concepts in php with realtime examples

Object-Oriented programming requires a different way of thinking about how you construct your applications
Share it:

oops concepts in php with realtime examples

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(){
    
    }
}
?>

The contractor to this object set class property 'name'. The accessor method getname(), enables you to fetch the value of the private member variable. Similarly, the username() method enables you to assign a new value to a variable.

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();    
}
?>

Access this file in your favorite browser, the output should be something like the following :

       The class name is: example1
       The class new name is: example2
Share it:

PHP

Post A Comment:

0 comments: