PHP Classes

Interface

interface Foo 
{
    public function doSomething();
}
interface Bar
{
    public function doSomethingElse();
}
class Cls implements Foo, Bar 
{
    public function doSomething() {}
    public function doSomethingElse() {}
}

Magic Methods

class MyClass
{
    // Object is treated as a String
    public function \_\_toString()
 {
        return $property;
    }
    // opposite to \_\_construct()
    public function \_\_destruct()
 {
        print "Destroying";
    }
}

Classes variables

class MyClass
{
    const MY\_CONST       = 'value';
    static $staticVar    = 'static';
    // Visibility
    public static $var1  = 'pubs';
    // Class only
    private static $var2 = 'pris';
    // The class and subclasses
    protected static $var3 = 'pros';
    // The class and subclasses
    protected $var6      = 'pro';
    // The class only
    private $var7        = 'pri';  
}

Access statically

echo MyClass::MY\_CONST;   # => value
echo MyClass::$staticVar; # => static

Inheritance

class ExtendClass extends SimpleClass
{
    // Redefine the parent method
    function displayVar()
 {
        echo "Extending class\n";
        parent::displayVar();
    }
}
$extended = new ExtendClass();
$extended->displayVar();

Constructor

class Student {
    public function \_\_construct($name) {
        $this->name = $name;
    }
      public function print() {
        echo "Name: " . $this->name;
    }
}
$alex = new Student("Alex");
$alex->print();    # => Name: Alex
Comments