6

私は、phpアプリケーションのいくつかを作成して構築する過程で、vars、=、およびクラス名の前にある&記号を見てきました。

これらがPHPリファレンスであることは理解していますが、私が見たり見たりしたドキュメントは、私が理解したり混乱させたりする方法でそれを説明していないようです。私が見た次の例をどのように説明して、それらをより理解しやすくすることができますか。

  public static function &function_name(){...}

  $varname =& functioncall();

  function ($var, &$var2, $var3){...}

とても有難い

4

2 に答える 2

4

2つの機能があるとしましょう

$a = 5;
function withReference(&$a) {
    $a++;
}
function withoutReference($a) {
    $a++;
}

withoutReference($a);
// $a is still 5, since your function had a local copy of $a
var_dump($a);
withReference($a);
// $a is now 6, you changed $a outside of function scope
var_dump($a);

したがって、引数を参照で渡すと、関数は関数スコープ外で引数を変更できます。

次に2番目の例です。

参照を返す関数があります

class References {
    public $a = 5;
    public function &getA() {
        return $this->a;
    }
}

$references = new References;
// let's do regular assignment
$a = $references->getA();
$a++;
// you get 5, $a++ had no effect on $a from the class
var_dump($references->getA());

// now let's do reference assignment
$a = &$references->getA();
$a++;
// $a is the same as $reference->a, so now you will get 6
var_dump($references->getA());

// a little bit different
$references->a++;
// since $a is the same as $reference->a, you will get 7
var_dump($a);
于 2013-02-27T18:27:06.327 に答える
0

参照関数

$name = 'alfa';
$address = 'street';
//declaring the function with the $ tells PHP that the function will
//return the reference to the value, and not the value itself
function &function_name($what){
//we need to access some previous declared variables
GLOBAL $name,$address;//or at function declaration (use) keyword
    if ($what == 'name')
        return $name;
    else
        return $address;
}
//now we "link" the $search variable and the $name one with the same value
$search =& function_name('name');
//we can use the result as value, not as reference too
$other_search = function_name('name');
//any change on this reference will affect the "$name" too
$search = 'new_name';
var_dump($search,$name,$other_search);
//will output string 'new_name' (length=8)string 'new_name' (length=8)string 'alfa' (length=4)

通常、同じインターフェースを実装したオブジェクトでメソッドを使用し、次に操作するオブジェクトを選択します。

参照による通過:

function ($var, &$var2, $var3){...}

例を見たと思いますので、いつどのように使うかを説明します。基本的なシナリオは、現在のオブジェクト/データに適用したい大きなロジックがあり、それを(メモリ内に)それ以上コピーしたくない場合です。お役に立てれば。

于 2013-02-27T18:54:41.327 に答える