2016-04-07 58 views
-2

我想了解的命名空間,包括在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無法找到...)

+1

爲什麼bash命令不只是PHP源代碼?爲什麼把修正放到附錄中,而不是直接修改代碼?這使得這一切都非常冗長和不清楚。 – syck

+0

Thanks @syck - 這裏有'bash'命令,這裏的讀者可以準確地重建我正在做的事情,我猜...我在附錄中添加了更正,所以可以跟蹤我的錯誤 - 我很難找到一個解釋這個的例子,所以我認爲記下可能出錯的地方是有用的......乾杯! – sdaau

+1

我想你想找到的是,你必須在調用以及被調用者類中使用'namespace'運算符。 'use'定義了別名。 – syck

回答

0

如果您在testin.php文件中使用use Foo\Bar;,那麼你可以直接使用$bar = new Bar();

如果你使用$bar = new Foo\Bar();,你不需要添加use ...

因爲use Foo只是意味着命名空間(在你的情況下,它意味着該文件夾「類」),如果你想讓它相當於一個指定的文件,你應該添加文件的名稱。