我想了解的命名空间,包括在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