Memory App
Programming
 




Resource

A resource can be: - 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)

<?php
    class foo {
        public $bar;
        protected $baz;
        private $bas;

        public $var1 = "Test"; // String
        public $var2 = 1.23; // Numeric value
        public $var3 = array (1, 2, 3);
    }
(1/4)

Final

Final visibility applies to methods and classes only.

<?php
    final class foo {
        
        final $c = 0; // Error: cannot declar property final

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

Constructors

Constructors (and all other magic methods) are normaly declared public (but constructors are private in patterns like Singleton). You can't initialize a variable by calling a function (that is done in constructor).

<?php
    class foo {
        public $a = init(); // Syntax error
        public function init() {}
    }
(3/4)

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.

<?php
        error_reporting(E_ALL);
        
        class Foo {
            public static $to = "World";
            public static function bar() {
                echo "Hello " . self::$to;
            }
        }

        echo foo::$to;
            // output: World
        
        $foo = new foo();
        $foo->bar();
            // output: Hello World
        
        echo $foo->to;
            // Notice: Undefined property: Foo::$to


Questions



Top Reference > Programming
0/0 (80)  
Not Logged