PROGRAMMING

 
REMEMBERS




Last update:   29-10-2021

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 
... 7 lines
 

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;
    }
}
... 4 lines
 

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
... 8 lines
 

Questions    
Class constants

        A B C D E F
🔔
1/6