minte9
LearnRemember



Resource

Public - accesed from any scope Protected - from within the class and its descendants Private - from within the class only Final - from any scope, but cannot be overriden in descendants
 
class A 
{
    public $a;
    protected $b;
    private $c;

    public $d = "Test"; // String
    public $e = 1.23; // Numeric value
    public $f = array (1, 2, 3);
}

$obj = new A();

$obj->a = 1;
$obj->c = 3; // Error:  Cannot access private property 

Final

Final visibility applies to methods and classes only. Final method cannot be overidden. Final class cannot be extended.
 
final class A
{
    final $c = 0; 
        // Error: final modifier is allowed ...
        // only for methods and classes

    final public function sum($a, $b) {
        return $a + $b;
    }
}

Constructors

Constructors are normaly declared public. Constructors are private in patterns like Singleton. You can't initialize a variable by calling a function. That is done in constructor.
 
class A
{
    public $a = init(); // Error: Invalid operations

    public function init() {}
}

Static

Static methods or properties can be access only as part of a class itself. This allows true encapsulation and avoid naming conflicts. Accessing static with -> generates notice.
 
error_reporting(E_ALL);

class A
{
    public static $to = "World";

    public static function bar()
    {
        echo "Hello " . self::$to;
    }
}

echo A::$to; // World

$obj = new A();
$obj->bar(); // Hello World

echo $obj->to; // Accessing static property A::$to as non static



  Last update: 402 days ago