1
私はこの全体のコンセプトを頭で覆そうとしています。私は頻繁に/グローバルに使用されるクラスのプロパティとメソッドを最上位の名前空間に配置し、他のクラスの内部でそれらを使用しようとしています。親ネームスペースでのPHPクラスの使用
だから私は名前空間がApp
呼ばれています:
ファイル名:core.phpの
namespace App;
class Core {
public function version() {
return '1.0';
}
}
ファイル名:のsettings.php
namespace App\Core;
use Core; // I know this is wrong
class Settings {
public function getCurrent() {
return 'The current version is: '.$this->Core->version(); // How do I do this?
}
}
ファイル名:
include('core.php');
include('settings.php');
$app = new App\Core;
echo $app->version(); // 1.0 OK...
echo $app->settings->getCurrent(); // Echo: The current version is: 1.0
index.phpを
上の例では、Core
クラス内のすべての関数を、他のクラスの他のクラスの内部でアプリ全体でどのように使用しますか?その後、
core.phpの
namespace App;
class Core {
public static function version() {
return '1.0';
}
}
のsettings.php
require('Core.php');
class Settings {
public function getCurrent() {
return 'The current version is: '.Core::version();
}
}
、最終的には::
'Core'クラスのオブジェクトを' Setting s ' –
これは、クラス内の他のオブジェクトのインスタンスを作成し、このインスタンスでクラスのメソッドを使用することは、実際には悪い考えです。あなたはクラスを再考するか、何をしようとしているかを説明する必要があります。 –
'Settings'のオブジェクトを作成するときに' Core'クラスのオブジェクトを作成し、 '** Settings'に** **パスします。コンストラクタの引数として、またはsetterメソッドを呼び出すことによって。はい、これは面倒ですが、最終的にはこれでよりうまくいくでしょう。長期的には、['Dependency Injection Container'](http://fabien.potencier.org/do-you-need-a- dependency-injection-container.html)を使用してください。 – Yoshi