Up to Speed with PHP: Classes, Constructors, Static Methods, Extensions and more


This is a brief post, outlining some of the essentials of working with classes in PHP.

Classes

A class in PHP is created very simply like this:
class MyClass {
}
and is instantiated using the following syntax:
$classInstance = new MyClass();

Constructors

Constructors are called when a class is instantiated. It is a method that is included under the umbrella term magic methods. These methods are identified by their double underscore prefix and are called automagically by the system.
class MyClass {
    function __construct() {
        echo "Hello World!";
    }
}

Variables

If we want to set variables then a constructor is the place to do it:
class MyClass {
    public $var;
    function __construct($var) {
        $this->var = $var;
        echo $var;
    }
}
Variables can be public, private or protected.
"Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member."
You'll notice the $this->var = $var; line, $this->var identifies the variable contained in the instance (or object).

Methods

Regular methods (of the non-magical kind) are declared using the function keyword and can be additionally specified as private, protected or public. (If none is given they are public.)
class MyClass {
    public $var;
    function __construct($var) {
        $this->var = $var;
        echo $var;
    }
    function printDate() {
        date_default_timezone_set('GMT');
        return date("l");
    }
}
$c = new MyClass("hi");
echo $c->printDate();
They are called on the class instance using the -> syntax.

Static Variables and Methods

Static (or class) methods are declared using the static keyword before them:
class MyClass {
    public $var;
    function __construct($var) {
        $this->var = $var;
        echo $var;
    }
    static function printDate($timezone) {
        date_default_timezone_set($timezone);
        return date("l");
    }
}

echo MyClass::printDate('GMT');
And called with a pair of colons between the class name and the method name.

Extensions and Parent Classes

To create an extension (or subclass) the extends keyword is used.
class MyChildClass extends MyClass {
    static function printDate($timezone) {
        return parent::printDate($timezone);
    }
}

echo MyChildClass::printDate('GMT');
To call a method within the parent class the parent keyword is employed. If instead you wish to call a static method within the current class then self is used:
class MyChildClass extends MyClass {
    static function printDate($timezone) {
       return self::className()." it's ".parent::printDate($timezone);
    }
    static function className() {
        return "MyChildClass";
    }
}
echo MyChildClass::printDate('GMT');

Final

The final keyword when placed before a class or a method makes it final. If we were to write
class MyClass {
    public static function printDate($timezone) {
        date_default_timezone_set($timezone);
        return date("l");
    }

    final static function className() {
        return "MyClass";
    }

}

class MyChildClass extends MyClass {
    static function printDate($timezone) {
        return self::className()." it's ".parent::printDate($timezone);
    }
}
then we could not add a className() method and so self would default to the parent class method of the same name. A class marked final, meanwhile, cannot be extended (subclassed).

Constants

To declare a constant use the const keyword:
class MyClass {

    const MY_CONSTANT = 10;

    function constantValue () {
        return self::MY_CONSTANT;
    }
}
And to employ the constant use the self:: (or parent::) syntax.

Type Hinting

There's limited type hinting in PHP.
class MyClass {

    function firstItem(Array $arr) {
        return $arr[0];
    }

}
$m = new MyClass();
$m->firstItem([1,2,3,4]);
But it doesn't extend to strings or ints.

Deconstructor

Finally (for this post) the deconstructor method is called when the instance goes out of existence:
function __destruct() {
    echo "kaboom!";
}

And there's more...

Before concluding it's important to mention further class-related elements, which include autoloading, traits, overloading, object iteration, cloning, comparison, late static bindings and serialization. In addition to which a full table of contents for classes is available.

Endorse on Coderwall

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Post a Comment