2016-12-16 8 views
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(); 
     } 

    } 

、最終的には::

+0

'Core'クラスのオブジェクトを' Setting s ' –

+3

これは、クラス内の他のオブジェクトのインスタンスを作成し、このインスタンスでクラスのメソッドを使用することは、実際には悪い考えです。あなたはクラスを再考するか、何をしようとしているかを説明する必要があります。 –

+1

'Settings'のオブジェクトを作成するときに' Core'クラスのオブジェクトを作成し、 '** Settings'に** **パスします。コンストラクタの引数として、またはsetterメソッドを呼び出すことによって。はい、これは面倒ですが、最終的にはこれでよりうまくいくでしょう。長期的には、['Dependency Injection Container'](http://fabien.potencier.org/do-you-need-a- dependency-injection-container.html)を使用してください。 – Yoshi

答えて

0

は今テストすることはできませんが、私はこのようsomethinghを行うだろう

include('Core.php'); 
include('Settings.php'); 

$app = new Settings; 

echo Core::version() // 1.0 OK... 
echo $app->settings->getCurrent(); // Echo: The current version is: 1.0 
関連する問題