Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 {

 require_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

like image 210
barfoon Avatar asked May 05 '11 16:05

barfoon


2 Answers

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.

like image 93
Lightness Races in Orbit Avatar answered Oct 22 '22 12:10

Lightness Races in Orbit


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.

like image 2
KingCrunch Avatar answered Oct 22 '22 13:10

KingCrunch