php[world] 2015 Schedule Announced


在 PHP 中引用意味着用不同的名字访问同一个变量内容。这并不像 C 的指针,替代的是,引用是符号表别名。注意在 PHP 中,变量名和变量内容是不一样的,因此同样的内容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身——变量名是目录条目,而变量内容则是文件本身。引用可以被看作是 Unix 文件系统中的 hardlink。

add a note add a note

User Contributed Notes 1 note

mike at eastghost dot com
1 year ago
If I make a function, using PHP 5.5.5:
function recurring_mailer_form( $form, $form_state ) {}

Is it the same as:
function recurring_mailer_form( $form,  & $form_state ) {}


Using php 5.5.x+

If you pass an object as usual (ie, without the ampersand), you can (only) alter the object's state (properties) (but not change the whole obj into a new obj)

$obj is an instance of the class Test which contains a member variable called hello:

function modify($obj) { $obj->hello = 'world (modified)!'; }

$obj->hello = 'world';
var_dump($obj->hello);  // outputs "world (modified!)"


Now, using the same code but assigning another value to $obj instead modifying the object's state results in no modification:

function modify($obj) { $obj = 42; }
var_dump($obj->hello);  // outputs "world"


Only accepting the parameter explicitly as a reference gives us the ability to completely change the variable's contents:

function modify(&$obj) { $obj = 42; }
var_dump($obj);         // outputs "42"

To Top