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?