PHP Class & Interface

PHP Class (Basic)

Sample PHP Class declaration

class MyClass
{
    const MESSAGE = 'hello world';            # Define a PHP class constant

    public static $s1 = 'greeting';           # PHP class variable

    public $v1 = 'welcome';                   # PHP class instance variable
    public $v2 = array(1,2);
    public $v3;

    function __construct($val=1)              # PHP class constructor
    {
       $v3 = 10 * $val;
    }

    function __destruct()                     # PHP class destructor
    {
       ...
    }

    public function hi()
    {
        echo $this->v1;                       # Access PHP instance variable in a class
        echo self::MESSAGE;                   # Access PHP constant within a class

    	static::greet();                      # Calling a static method
    }

    public static function greet()
    {
        echo self::$s1;                       # Access PHP static data within a class
    }
}

Instantiate a new PHP class

$test = new MyClass(10);
  • "this" refers to the instance of an object
  • "self" refers to the class
  • __CLASS__ refers to the name of the current class

Static class functions, static variables & constant

Calling PHP static function

MyClass::greet();
$test->greet();

Access PHP class variable

MyClass::$s1;
$test::$s1;

Access PHP class constant

MyClass::MESSAGE;
$test::MESSAGE;

Access instance methods and variables

Access PHP instance methods and instance variables

$test->hi();
$test->v1;

Extending PHP class

Extending a PHP class

class MyChildClass extends MyClass            # Inheritance (Extend a PHP class)
{
    function __construct() {
       parent::__construct();                 # Calling PHP parent constructor
       ...
    }

    function hi() {
        parent::hi();                         # Invoke parent class
    }
}
$child = new MyChildClass();
$child->hi();

Class name & variable substitution

Class name substitution

$name = 'MyClass';                            # new a class by name
$test = new $name(10);
$test->hi();

Class variable name substitution

$s = "v1";
$test->$s;                                    # Same as $test->v1

Initialize PHP instance variable

Initiate class instance variable

public $a = 3;
public $str1 = <<<'EOT'
A single line
of string
EOT;

Initialize by

  • nowdocs
  • Literal
  • Does not allow expression like 10*2

PHP Class final key word

Declare final for PHP class and methods

# Declare the class can not be extended
final class MyClass {

   # Cannot extend this method by children class
   final public function m1() {
   }
}

PHP Variable and Method Visibility

Apply to method and variables

PHP visibility key word Scope
public To all
protected To itself and sub-classes
private To itself only

PHP Object Comparison

== Both objects are of same class & all attributes have the same values
=== Both are the same instance

PHP Abstract class

Declare an abstract PHP class

# Declare an Abstract class
abstract class AbstractClass
{
    # declare an abstract method
    abstract public function hi();

    public function shared_greeting() {
      echo 'hi!';
    }
}

PHP Interface

Declare a PHP interface

interface SayHi extends Say, Greeting         # Can extends 0 or more interface
{
    const MESSAGE = 'Interface constant';     # Can be accessed by SayHi::MESSAGE

    public function hi();
}

class MyClass implements SayHi {
...
}

Pre-defined interface

  • Iterator, IteratorAggregate: Indicate a class supports foreach operation
  • ArrayAccess: Indicate array type access
  • Serializable: Customized serialization

PHP Overloading Methods

The definition of overloading is very different from other Object oriented language

Overloading methods are invoked when accessing properties or methods that have not been declared or are not visible in the current scope

Method invoked Called when
__set() when setting inaccessible instance variable
__get() when getting inaccessible instance variable
__isset() isset() or empty() on inaccessible instance variable
__unset() unset() on inaccessible instance variable
__call() accessing inaccessible methods
__callStatic() accessing inaccessible static methods

Implement PHP overloading methods

class MyClass
{
    public function __set($var_name, $value) {
        $this->data[$var_name] = $value;
    }

    public function __get($var_name) {
        if (array_key_exists($var_name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property: ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }
}

PHP Build-in Methods

PHP Cloning

$v = new MyClass();
$v->a = 30;
$c = clone $v;

PHP use shallow cloning. Developer can implement __clone to create a deep cloning

public function __clone() {
   $this->o1 = clone $this->o1;
}

Other Built in PHP method

Method name Invoke
__sleep before serialize() is called
__wakeup before unserialize() is called
__toString called when the object need to cast to a string value
__invoke($v) $a = new MyClass(); $a(5) # call when call the object like a function
__clone when cloning an object

Serialize & unserialize PHP class

Serialize a PHP class and store the data in a file

$a = new MyClass;
$str = serialize($a);

file_put_contents('data', $str);

Retrieve the data from a file and un-serialize it back to a PHP class

$s1 = file_get_contents('data');
$a1 = unserialize($s1);

PHP Introspection

Finding Class methods

$class = 'MyClass';

class_exists($class);                     # TRUE if class exists

$classes = get_declared_classes();        # Get all classes

get_parent_class($class);                 # Get parent class

# All of the below are the same
$methods = get_class_methods($class);
$methods = get_class_methods(MyClass);
$methods = get_class_methods('MyClass');

$variables = get_class_vars($class);      # Get varaibles

$obj = new MyClass();

if (is_object($obj)) {
    $classname = get_class($obj);         # Return the object class name
    get_object_vars($obj);                # Return array containing key/value
    method_exists($obj, 'hi');            # TRUE if method exists
}

PHP Class Functions

Functions Description
class_alias Create a class alias
class_exists Class exist
get_called_class Get the called class
get_class_methods Get the class methods' names
get_class_vars Variables of the class
get_class The name of the class of an object
get_declared_classes An array of defined classes
get_declared_interfaces An array of declared interfaces
get_object_vars Variables of an object
get_parent_class Parent class
interface_exists Is interface exists
is_a Is a class
is_subclass_of Is a sub-class
method_exists Method exist
property_exists Property exist

Implement PHP Class Iterator

Implement an iterator for a PHP class

class MyClass implements Iterator
{
    private $data = array();

    public function __construct($values)
    {
        if (is_array($values)) {
            $this->data = $values;
        }
    }

    public function rewind() {
        reset($this->data);
    }

    public function current() {
        return current($this->data);
    }

    public function key() {
        return key($this->data);
    }

    public function next() {
        return next($this->data);
    }

    public function valid() {
        return $this->current() !== false;
    }
}

$v = array('a','b','c');
$iterator = new MyClass($v);

foreach ($iterator as $key => $value) {             # Iterate through each element
    echo "$key: $value ";
}

Implement PHP Singleton Pattern

class Manager
{
    private static $instance;


    public static function get_instance()
    {
        if (!isset(self::$instance)) {
            $class_name = __CLASS__;
            self::$instance = new $class_name;
        }

        return self::$instance;
    }

    public function hi()
    {
        echo 'hi';
    }

    public function __clone()
    {
        trigger_error('Clone is not allowed for singleton object.', E_USER_ERROR);
    }

}

Manager::get_instance()->hi();