我想了解的命名空間,包括在PHP中,並用看起來像這樣的例子上來:PHP,命名空間,使用,包括 - 簡單的例子錯誤
$ tree test/class/
test/class/
├── Bar.php
└── testin.php
下面是bash
命令我「M運行示例設置如下:
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
當我運行此我得到:
+ 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
好了,我怎麼能修改這個例子,所以它testin.php
讀取Bar.php
中的類,並使用use
和名稱空間實例化一個對象?
編輯:第二個文件設置應該有 「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:如果我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
......但後來,什麼是use
點,如果我不得不重複完整的命名空間路徑做$bar = new \Foo\Bar();
什麼時候? (如果我不明確寫入\Foo\Bar()
,那麼類Bar
無法找到...)
爲什麼bash命令不只是PHP源代碼?爲什麼把修正放到附錄中,而不是直接修改代碼?這使得這一切都非常冗長和不清楚。 – syck
Thanks @syck - 這裏有'bash'命令,這裏的讀者可以準確地重建我正在做的事情,我猜...我在附錄中添加了更正,所以可以跟蹤我的錯誤 - 我很難找到一個解釋這個的例子,所以我認爲記下可能出錯的地方是有用的......乾杯! – sdaau
我想你想找到的是,你必須在調用以及被調用者類中使用'namespace'運算符。 'use'定義了別名。 – syck