2016-04-07 64 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只是意味着命名空间(在你的情况下,它意味着该文件夹“类”),如果你想让它相当于一个指定的文件,你应该添加文件的名称。