简体   繁体   中英

Setting undeclared property doesn't work in PHP 5.3.x?

Can anyone tell me why:

class foo {

    function __construct() {
        foreach($_GET as $get_var => $val) {
            $this->$get_var = $val;
        }

        foreach($_POST as $post_var => $val) {
            $this->$post_var = $val;
        }

        $this->test = "test";
    }
}

Generates and empty object ie

object(foo)#1 (0) {   
}

yet:

class foo {

public $post;
public $get;


function __construct() {
        foreach($_GET as $get_var => $val) {
            $this->get->$get_var = $val;
        }

        foreach($_POST as $post_var => $val) {
            $this->post->$post_var = $val;
        }
    }
}

Works just fine ie:

object(foo)#1 (2) {
  ["post"]=>
  NULL
  ["get"]=>
  object(stdClass)#3 (2) {
    ["fred"]=>
    string(4) "fish"
    ["joe"]=>
    string(6) "bloggs"
  }
}

It only seems to be an issue in PHP 5.3.x yet it works in 5.2.x on our machines at work. Is it a PHP config issue or am I missing something? I looked in the Classes and Objects docs and can't see anything.

It's not a big issue for this class but when it comes to building database classes it means a LOT more work.

yes, it's a 5.3 issue. actually you shouldn't be depending on undeclared variable usage but here is some solutions.

http://www.tonylake.info/?p=159

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM