Monday, December 17, 2012

A simple PHP class demo




I'll give two examples of basic PHP classes here. PHP class definitions begin with the keyword class,
followed by a class name, followed by a pair of curly braces which includes the definitions of the properties and methods  belonging to the class.

 PHP class is also object oriented, with inheritance, encapsulation and  polymorphism.
SimpleClass.php
<?php
//Simple PHP class demo, Jiansen Lu
class SimpleClass
{
    // property declaration
    public $var = 'Hello World!';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}
?>

example1.php, calls SimpleClass.php
<?php
include 'SimpleClass.php';
$instance = new SimpleClass();
$instance->displayVar();
?>


Run example1.php, produces "Hello World!"
inheritance.php, inheritance class redefined constructor and method displayVar()
 <?php
//PHP inheritance demo
include 'SimpleClass.php';
class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    public function __construct($var) {
    $this->var = $var;
  }
    function displayVar()
    {
        echo $this->var.'<br />';
        echo "Extending class <br />";
        parent::displayVar();
    }
}

$extended = new ExtendClass("PHP inheritance demo");
$extended->displayVar();
?>

Run inheritance.php, produced:
"PHP inheritance demo
Extending class
PHP inheritance demo"
More in this video:




No comments:

Post a Comment