クラス内のすべての関数で使用できるように変数を定義することは可能ですか...
例えば:
class scope {
private $db = null;
function __construct($db) {
$this->db = mysqli_init();
return $this->db;
}
function uses_variable {
$stmt = $db->stmt_init();
}
}
しかし、変数をグローバルにしたり、余分な不要なコードやオーバーヘッドを大量に使用したりせずに?
編集
次のようなものを使用して、すべてのクラスをインデックスにロードしています。
class autoloader {
public static $loader;
public static function init()
{
if(self::$loader == NULL) {
self::$loader = new self();
}
return self::$loader;
}
public function __construct() {
spl_autoload_register(array(this, 'library'));
request::request();
template::render();
}
public function library($class)
{
set_include_path(get_include_path() . PATH_SEPARATOR . '/lib');
spl_autoload_extensions('.class.php');
spl_autoload($class);
}
}
uses_variable 関数で変数を呼び出すと、次のようにするとエラーが表示されます。
function uses_variable () {
$stmt = $this->db->stmt_init();
}
Notice: Undefined property: autoloader::$db
、関数 user_variable がオートローダーでロードされた別のクラスで呼び出されることに注意する価値があるかもしれません。これによりプロジェクトのスコープが変更されるのではないかと思います。><.