最初に基本クラスの新しいインスタンスを作成し、次にその基本クラス内からサブクラスの新しいインスタンスを作成できるようにしたいと考えています。また、サブクラス内から基本クラスのメソッドを呼び出せるようにしたいと考えています。以下のコードで試してみましたが、思いどおりに動作しますが、これは悪い習慣であり、メモリ効率は良いのでしょうか? 他にコメントはありますか?
<?php
class BaseClass {
private $subclass = NULL;
function __construct() {
print "In BaseClass constructor<br>";
$this->subclass = new SubClass();
}
function sayhello() {
print 'hello from base class';
}
}
class SubClass extends BaseClass {
function __construct() {
print "In SubClass constructor<br>";
$this->sayhello();
}
function saygoodbye($num) {
print 'goodbye from base class';
}
}
$SUB = new SubClass();
?>
$this->
これを行う私の意図は、CodeIgniter がどのように機能するかなど、を使用してすべてにアクセスできるようにすることでした。これは、プライベート API の index.php ファイルにあるものです。call_user_func_array() を呼び出す前に API リクエストを認証できるようにしたいと考えています。認証用のデータベースにも接続する必要がありますが、サブクラスからもDBにアクセスできるようにしたいです。基本的に、コードは呼び出されている API メソッドを特定し、サブクラスのインスタンスを作成して、最後にメソッドを呼び出します。
$get_contents = $_GET;
$resource_name = $get_contents['_resource'];
unset($_GET['_resource']);
$resource_method = $get_contents['_resource_method'];
unset($_GET['_resource_method']);
//Load the resource class
include 'core/resources/' . $resource_name . '.php';
//If set to true, each method will require an API key to be used
$auth_required = array();
$auth_required['collections']['addcollection'] = TRUE;
if(isset($auth_required[$resource_name][$resource_method]) && $auth_required[$resource_name][$resource_method] == TRUE) {
print 'requires auth';
}
//Create a new instance of the resource
$API = new $resource_name();
$method_params = $_GET;
call_user_func_array(array(&$API, $resource_method), $method_params);