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
Questions and answers
Protected property can be accessed only from the ...
- a) current class
- b) current class and its descendants
Final property applies to:
- a) classes and methods
- b) classes, methods and properties
A class constant cannot be declared final.
- a) false
- b) true
Static properties are accesible as part of the:
- a) class
- b) instance
How do you call a constant "TO" from a class foo?
- a) foo::$TO
- b) foo::TO
How do you call static property "to" from a class "foo"?
- a) foo::$to
- b) foo::to