开发者

why class attribute assign by reference doesn't work?

开发者 https://www.devze.com 2023-02-19 22:00 出处:网络
class c{ public $myV = &$_GET; } it 开发者_JAVA技巧gives me error :( if i do a plain simple: $myV = &$_GET;
class c{
    public $myV = &$_GET;
}

it 开发者_JAVA技巧gives me error :(

if i do a plain simple:

$myV = &$_GET;

it works


You cannot even do this:

public $x = $y;

From the manual:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

To get around this, just set it in the __construct function.

public function __construct()
{
  $this->myV = &$_GET;
}


... but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

from php.net : Properties

You can define this dependency in a constructor though.


Try this:

class c {
    public $myV;

    function c() {
        $this->myV = &$_GET;
    }
}

You cannot assign variables to fields before a class is instantiated. This way, your variable will be set when an object is made from your class.


You can achieve a similar effect like:

class c{
   public $myV;
   function __construct() { $this->myV = &$_GET; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消