• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

php namespace与use的问题

php 搞代码 4年前 (2022-01-23) 21次浏览 已收录 0个评论
文章目录[隐藏]

/test文件夹下建立C.php文件,内容
<?php
namespace Test\Driver;
class C
{
function test()
{
echo “c”;
}
}

?>

/下建立test.php文件,内容

<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
无标题文档

<body>
<?php
include “test/C.php”;
use Test\Driver;
$c=new C();
$c->test();
echo “
“;

?>

运行错误:
( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Class ‘C’ not found in E:\hongyunlai\thinkphp32\test.php on line 14
Call Stack
# Time Memory Function Location
1 0.0006 247520 {main}( ) ..\test.php:0

回复讨论(解决方案)

如果test.php文件

include “test/C.php”;
$c=new Test\Driver\C();
$c->test();
echo “
“;

这么写的话,就可以正常的显示出来

c

的内容

include "test/C.php"; use Test\Driver as p;$c=new p\C();$c->test();

恩,这样写是可以的。但是必须要这么写吗?

不好意思,请问use 不是引用当前的命名空间里了吗?

这样子也可以

namespace Test\Driver;include "test/C.php"; $c=new C();$c->test();

use 是引用命名空间
正确的用法我也不是很清楚

引用空间名,不是把命名空间下的类都引用过来了吗?
不是在这个命名空间下的类,都可以直接的使用吗?

。本文来源gao!%daima.com搞$代*!码网1

搞代gaodaima码

现在操作上,感觉use没起到什么作用。

刚才恶补了一下,现炒现卖
使用命名空间的三种方法

include "test/C.php"; $c=new Test\Driver\C();$c->test();

include "test/C.php"; use Test\Driver;$c=new Driver\C();$c->test();

include "test/C.php"; use Test\Driver as p;$c=new p();$c->test();

引用空间名,不是把命名空间下的类都引用过来了吗?
只要你 include 了,里面的所用类就都加载了

什么选择性载入是不存在的,自欺欺人的

第一种和第三种我都明白

include “test/C.php”;
use Test\Driver;
$c=new Driver\C(); 就是不明白这里的Driver 是什么意思
$c->test();

你的命名空间是 Test\ Driver
$c=new Driver\C(); 只需取命名空间的最后一节即可

呀,手欠做了个试验

<?php
namespace Test\Driver;
use Test\Driver;
class C
{
function test()
{
echo “c”;
}
}

?>

test.php
<?php

include “test/C.php”;
//use Test\Driver;
$c=new Test\Driver\C();
$c->test();
echo “
“;

?>

这样写又报错了

include “test/C.php”;
//use Test\Driver;
$c=new Driver\C();
$c->test();
echo “
“;

报错信息
( ! ) SCREAM: Error suppression ignored for
( ! ) Fatal error: Class ‘Driver\C’ not found in E:\hongyunlai\thinkphp32\test.php on line 14
Call Stack
# Time Memory Function Location
1 0.0005 247472 {main}( ) ..\test.php:0


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:php namespace与use的问题

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址