Studyon Minte9.com
ZCE 5.3

Study

Fundamentals



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

<?php class myClass { // Class contents go here } $myClassInstance = new myClass(); // --- Look Here --- // // instantiation is done by 'new' constructor
  An object is always passed by reference (different from others type of variables). Variables are not passed by reference (& needed)
<?php $a = 1; $b = $a; $a = 2; echo $b; // output 1 $a = 1; $b = &$a; // --- Look Here --- // $a = 2; echo $b; // output 2
  Reference with foreach changes the array
<?php $arr = array('1', '2', '3', '4'); foreach ($arr as $val) { // Without reference $val *= 2; } print_r($arr); // $arr = array('1', '2', '3', '4'); // The array is not changed foreach ($arr as &$val) { // --- With reference --- // $val *= 2; } print_r($arr); // $arr = array('2', '4', '6', '8'); // --- The array is changed --- //
  Reference with two foreach has unexpected behavior, use it with care
<?php $a = array('a', 'b'); foreach ($a as &$v) {} // 1: $a[0] = a / $a[1] = b / $v = a / $a[0] = &$v // 2: $a[0] = a / $a[1] = b / $v = b / $a[1] = &$v print_r($a); // { a, b } foreach ($a as $v) {} // 1: $a[0] = a / $a[1] = &$v / $a[1] = a // 2: $a[0] = a / $a[1] = a / $v = a print_r($a); // { a, a } // --- Look Here --- //
  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 // --- Look Here --- //
  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"; // --- Look Here --- // } } 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
 


http://www.phpf1.com/tutorial/php-foreach-loop.html
http://schlueters.de/blog/archives/141-References-and-foreach.html