开发者

Why can't you have require* statements in a class definition?

开发者 https://www.devze.com 2023-03-04 09:28 出处:网络
Possibly Related: Why don't PHP attributes allow functions? Pardon me if this has been asked before, but why can you not have something like the following:

Possibly Related:

Why don't PHP attributes allow functions?

Pardon me if this has been asked before, but why can you not have something like the following:

class foo {

 r开发者_StackOverflow中文版equire_once 'defines.php';

 private $_server = DB_SERVER;
 private $_username = DB_USERNAME;
 private $_password = DB_PASSWORD;
 private $_database = DB_NAME;
 public  $debug = false;
 public $_conn;

 function __construct() {                          
    $connection = @mysqli_connect($this->_server, $this->_username, $this->_password, $this->_database);
 }

 ...

}

Cheers,

EDIT: Looking to find out why this behaviour exists and why its not possible. How come the votes to close?

EDIT2 : Would also like to re-open this


It was possible to require and include files both within function scope and at global scope, before Classes were added to PHP.

This is only a guess — I'm not sure what else we could do other than for the language designers to come and tell us their story — but I imagine it was believed that no benefit would be gained from adding this functionality to the "new scope" invented by the addition of Classes, especially considering the complexity added to the back-end in order to support it.

It's also not entirely clear what the scoping rules would be for any declarations made inside the required file.

In conclusion, I think you're asking the wrong question. Instead of "why isn't this supported?" it's more a case of "why should it be supported?".

I hope that this helps in some small way.


It is because in the class definition "real" code is not allowed at all, only definitions for properties, methods and constants are allowed. You can put your include-statements into "main-scope" (procedural), functions and methods, like every other code.

class A {
  var $a = 1 + 1; // Parse error: unexpected '+'
}

However, as far as I know its not supported in any language. For example java uses static code blocks for this

class A {
  private static int a = 0;
  static {
    a = 1+1;
  }
}

In PHP just put your "static" code after the class itself.

class A {}
/* static */ {
  // do something
}

Its not possible to access private or protected static members this way.

0

精彩评论

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

关注公众号