Memory App
Programming
 




A class is only a blueprint, it must be instantiated into object before use.

<?php
    class myClass { 
        // Class contents go here
    }
    $myClassInstance = new myClass();
        // instantiation is done by 'new' constructor
An object is always passed by reference (different from others type of variables). For Object & are not needed (reference by default, but not in PHP 4).

<?php 
    class A {
        public $foo = 1;
    }  

    $a = new A;    
    $b = $a; // both $a and $b will point to the same object

    echo $a->foo; // output 1
    $a->foo = 2;
    echo $b->foo; // output 2
Object reinstantiation breaks the reference

<?php
    class myClass { 
        public $foo;
        public function __construct($val) {
            $this->foo = $val;
        }
    }

    $a = new myClass(1);
    $b = $a;

    echo $a->foo; // output 1        
    $a->foo = 2; 
    echo $b->foo; // output 2
    
    $a = new myClass(2); 
    echo $a->foo; // output 2
    echo $b->foo; // output 1 // reference is broken
Class Inheritance allows a class to extend another class. Parent classes can be accessed using the special parent:: namespace.

<?php
    class A {
        function test() {
            echo "A::test";
        }
        function func() {
            echo "A::func";
        }
    }

    class B extends A {
        function test() {
            parent::test();
            echo "B:test";
        }
    }

    class C extends B {
        function test() {
            A::test();
        }
    }

    $a = new A();
    $b = new B();
    $c = new C();

    $a->test(); // A::test
    $a->func(); // A::func
    
    $b->test(); // A::test / B::test
    $b->func(); // A::func

    $c->test(); // A::test


Questions



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