How do you pass objects by reference in PHP 5?

后端 未结 3 1789
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 03:58

In PHP 5, are you required to use the & modifier to pass by reference? For example,

class People() { }
$p = new People();
function one($a) {         


        
3条回答
  •  生来不讨喜
    2020-11-30 04:40

    You're using it wrong. The $ sign is compulsory for any variable. It should be: http://php.net/manual/en/language.references.pass.php

    function foo(&$a)
    {
    $a=null;
    }
    
    
    foo($a);
    To return a reference, use
    
     function &bar($a){
    $a=5;
    return $a
    
     }
    

    In objects and arrays, a reference to the object is copied as the formal parameter, any equality operations on two objects is a reference exchange.

    $a=new People();
    $b=$a;//equivalent to &$b=&$a roughly. That is the address of $b is the same as that of $a 
    
    function goo($obj){
    //$obj=$e(below) which essentially passes a reference of $e to $obj. For a basic datatype such as string, integer, bool, this would copy the value, but since equality between objects is anyways by references, this results in $obj as a reference to $e
    }
    $e=new People();
    goo($e);
    

提交回复
热议问题