私は名前空間を理解しようとすると、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.php
はBar.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
が...見つけることができません)
なぜPHPソースだけでなく、bashコマンドですか?なぜ訂正を付録に入れて、コードを直接変更しないのですか?それはすべて非常に冗長で不明瞭になります。 – syck
Thanks @syck - 「bash」コマンドは、ここの読者が私がやっていることを正確に再現できるように、そこにあります。そして私は付録に訂正を追加しました。私は間違いが何であるかを追うことができます。これを説明する例があるので、どこが間違っているかを書き留めることは有益だと思います。乾杯! – sdaau
あなたが知りたいのは、呼び出し側クラスと呼び出し側クラスで 'namespace'演算子を使う必要があるということです。 'use'はエイリアスを定義します。 – syck