2016-04-07 8 views
-2

私は名前空間を理解しようとすると、PHPに含まれており、このように見える例を思い付いたんだ。ここではPHP、名前空間、使用および含ま - 簡単な例エラー

$ tree test/class/ 
test/class/ 
├── Bar.php 
└── testin.php 

は私がbashコマンドですそう、

+ php testin.php 
PHP Warning: The use statement with non-compound name 'Foo' has no effect in /tmp/test/class/testin.php on line 2 
PHP Parse error: syntax error, unexpected '=' in /tmp/test/class/testin.php on line 4 

OK:

mkdir -p test/class 

cat > test/class/Bar.php <<EOF 
<?php 
namespace Foo; 
class Bar { 
    function __construct() { // php 5 constructor 
    print "In Bar constructor\n"; 
    } 
    public function Bar() { // php 3,4 constructor 
    echo "IT IS Bar\n"; 
    } 
} 
?> 
EOF 

cat > test/class/testin.php <<EOF 
<?php 
use Foo; 
require_once (__DIR__ . '/Bar.php'); 
$bar = new Bar(); 
?> 
EOF 

pushd test/class 
php testin.php 
popd 

をそして、私はこれを実行したときに私が手:「例をセットアップするために実行しているメートルこの例を変更するにはどうすればよいですか?testin.phpBar.phpのクラスを読み取り、オブジェクトをインスタンス化します。useと名前空間を使用していますか?


EDIT:第二のファイルの設定は "EOFは" 理由はドル記号$の存在により、引用されている必要があります

cat > test/class/testin.php <<"EOF" 
<?php 
use Foo; 
require_once (__DIR__ . '/Bar.php'); 
$bar = new Bar(); 
?> 
EOF 

...その後、PHPスクリプトを実行すると、エラーを与える:

+ php testin.php 
PHP Warning: The use statement with non-compound name 'Foo' has no effect in /tmp/test/class/testin.php on line 2 
PHP Fatal error: Class 'Bar' not found in /tmp/test/class/testin.php on line 4 

EDIT2:I declare the full path, beginning with \ which signifies the root namespace場合、それは動作します:

cat > test/class/testin.php <<"EOF" 
<?php 
use \Foo; 
require_once (__DIR__ . '/Bar.php'); 
$bar = new \Foo\Bar(); 
?> 
EOF 

...そしてすべてが動作します:

+ php testin.php 
In Bar constructor 

...が、その後$bar = new \Foo\Bar();を行うとき、私は完全な名前空間のパスを繰り返す必要があれば、useのポイントは、何ですか? (私は明示的に\Foo\Bar()を書いていない場合、そのクラスBarが...見つけることができません)

+1

なぜPHPソースだけでなく、bashコマンドですか?なぜ訂正を付録に入れて、コードを直接変更しないのですか?それはすべて非常に冗長で不明瞭になります。 – syck

+0

Thanks @syck - 「bash」コマンドは、ここの読者が私がやっていることを正確に再現できるように、そこにあります。そして私は付録に訂正を追加しました。私は間違いが何であるかを追うことができます。これを説明する例があるので、どこが間違っているかを書き留めることは有益だと思います。乾杯! – sdaau

+1

あなたが知りたいのは、呼び出し側クラスと呼び出し側クラスで 'namespace'演算子を使う必要があるということです。 'use'はエイリアスを定義します。 – syck

答えて

0

あなたtestin.phpファイルでuse Foo\Bar;を使用する場合は、直接$bar = new Bar();を使用することができます。

あなたが$bar = new Foo\Bar();を使用している場合、あなたはuse Fooだけの名前空間を意味するので、あなたはそれが任命されたファイルに対応したい場合は、(あなたのケースで、それはフォルダ「クラス」を意味します)use ...

をすべき追加は必要ありません。ファイルの名前を追加します。

関連する問題