I decided to get acquainted with the classes, and I met this error:

Fatal error: Uncaught Error: Call to a member function prepare() on null in C:\servers\WWW\engine\engine.php:14 Stack trace: #0 C:\servers\WWW\index.php(5): le->query('SELECT * FROM `...', Array) #1 {main} thrown in C:\servers\WWW\engine\engine.php on line 14 

My code is:

 class le { function __construct() { $set = json_decode(file_get_contents('engine/settings.json'), true); $lang = json_decode(file_get_contents('engine/languages/'.$set['ui']['language'].'.json'), true); $tpl = unserialize(file_get_contents('engine/templates/'.$set['ui']['template'].'.serialize')); $db = new PDO('mysql:host='.$set['db']['host'].';dbname='.$set['db']['name'].';charset=utf8',$set['db']['user'],$set['db']['pass']); } public function query($sql, $params) { global $db; $query = $db->prepare($sql); $query->execute($params); return $query; } .... 

Judging by the error, I realized that the function 'query' cannot find the variable 'db'.

How to make this function have access to 'db'?

Moreover, every time the function is called 'db' should not be reinitialized.

And in general, how to make global variables in classes correctly?

  • it is necessary to make a class field - Alexey Shimansky

1 answer 1

You can either pass the value to the constructor.

 class Le { public static $db; public function __construct($db) { // Ваш код self::$db = $db; } } // Получили ресурс $db = 'Ресурс'; $obj = new Le($db); echo Le::$db; 

Or get the value directly in the constructor

 class Le { public static $db; public function __construct() { // Получили ресурс $db = 'Ресурс'; // Ваш код self::$db = $db; } } $obj = new Le; echo Le::$db; 

And then refer to the static property of the class $ db.

  • 'db' is essentially a class in a function. Ie through it I start the pdo mysql database driver. Added self :: $ db = $ db; Now writes: Fatal error: Uncaught Error: Access to undeclared static property: le: $ db in C: \ servers \ WWW \ engine \ engine.php: 9 Stack trace: # 0 C: \ servers \ WWW \ index.php (3): le -> __ construct () # 1 {main} thrown in C: \ servers \ WWW \ engine \ engine.php on line 9 - user272078
  • @ user272078 There is such a concept of "scope" - read about it, first with examples of user-defined functions - it will be easier to understand how to pass parameters, since The user function is essentially the same method in the class body, with no big differences. - Edward