Created
July 3, 2016 19:36
-
-
Save bulton-fr/bde0dba23abbdcc1d2c97f8438b16f82 to your computer and use it in GitHub Desktop.
code igniter develop : function load_class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @see : https://github.com/bcit-ci/CodeIgniter/blob/develop/system/core/Common.php#L141 | |
* Return a reference is useless ! | |
* To explain : https://youtu.be/_84eIkA3j54?t=13m48s | |
*/ | |
//Code example: | |
//Create a Foo class with a attribute | |
class Foo | |
{ | |
protected $attr; | |
public function __construct($attr) | |
{ | |
$this->attr = $attr; | |
} | |
} | |
//Declare function without return reference | |
function loadclass() { | |
$foo = new Foo('bar'); //Instance Foo with bar attribute | |
echo 'Foo1 : '; | |
var_dump($foo); //Display Foo instance from the fonction | |
echo '<br>'; | |
return $foo; | |
} | |
//Declare function with return reference like code igniter | |
function &loadClass2() { | |
$foo = new Foo('baz'); //Instance Foo with bar attribute | |
echo 'Foo2 : '; | |
var_dump($foo); //Display Foo instance from the fonction | |
echo '<br>'; | |
return $foo; | |
} | |
$foo1 = loadClass(); //Get the Foo instance without reference | |
$foo2 = &loadClass2(); //Get the Foo instance with reference | |
//Display Foo instances | |
echo '<br>'; | |
echo 'Foo1 return : '; | |
var_dump($foo1); | |
echo '<br>'; | |
echo 'Foo2 return : '; | |
var_dump($foo2); | |
//Display zval object | |
echo '<br><br>'; | |
debug_zval_dump($foo1); | |
echo '<br><br>'; | |
debug_zval_dump($foo2); | |
/** | |
* From PHP 5.2 to PHP 7.0, the result is : | |
* | |
* Foo1 : object(Foo)#1 (1) { ["attr":protected]=> string(3) "bar" } | |
* Foo2 : object(Foo)#2 (1) { ["attr":protected]=> string(3) "baz" } | |
* | |
* Foo1 return : object(Foo)#1 (1) { ["attr":protected]=> string(3) "bar" } | |
* Foo2 return : object(Foo)#2 (1) { ["attr":protected]=> string(3) "baz" } | |
* | |
* object(Foo)#1 (1) refcount(2){ ["attr":protected]=> string(3) "bar" refcount(1) } | |
* | |
* object(Foo)#2 (1) refcount(2){ ["attr":protected]=> string(3) "baz" refcount(1) } | |
*/ | |
// The both Foo object save they instance. The reference is useless. | |
// View the youtube link to understand why. The table at that time explain how PHP save instance in memory. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment