这一小节里面的示例敲出来报错啊
宝怡
宝怡 2019-07-23 13:28:20
[PHP讨论组]

用use导入命名空间的时候 会显示语法错误,或者显示命名空间中的类已经定义了啊

的php版本是7.2.10

宝怡
宝怡

全部回复(3)
王先生

我调整了一下调用代码的位置就可以了。哪个地方需要调用,就写在他的前面。(老师的正常显示,我们的不能正常显示其实我也搞不清楚问题在哪里。以后在编程的过程中注意不要重名就好了或者用其他方式规避重名,不一定要完完全全按照老师的来)

<?php

namespace Demo2;

// use function Demo1\test as testAA;

function test($a,$b)

{

  return $a+$b;

}

echo test(4,5) ;// 非限定命名空间

require('test1.php');

use const \demo1\CITY;

use const \demo1\COUNTRY;

use function \Demo1\test;

echo "<hr>";

echo test(4,5);

echo "<hr>";

echo '调用test1中的常量:'.COUNTRY.'---';

echo CITY;


 ?>


王先生

和老师一样的代码,报错:

Fatal error: Cannot declare function Demo2\test because the name is already in use in E:\wwwroot\phpbase\object\namespace\test2.php on line 5

test1代码:

<?php 

namespace Demo1;

function test($a,$b)

{

  return $a*$b;

}

?>

test2代码:

<?php

namespace Demo2;

require('test1.php');

use function Demo1\test;

function test($a,$b)

{

  return $a+$b;

}

echo test(4,5) ;// 非限定命名空间

echo "<hr>";

echo test(4,5);

 ?>


天蓬老师

把源代码,还有出错提示全部贴上来看一下

  • 回复 test1.php代码: <?php namespace Demo1; class test1 { private $name = 'www.php.cn'; public function getName() { return $this->name; } } test2.php代码: <?php namespace Demo2; require('test1.php'); // use 默认从全局开始引入 use Demo1\test1; class test1 { private $name = 'php中文网'; public function getName() { return $this->name; } } echo (new namespace\test1)->getName(); echo '<hr/>'; 报错提示: Fatal error: Cannot declare class Demo2\test1 because the name is already in use in D:\phpstudy\PHPTutorial\WWW\dododo\php\phpCh\chapter07\test2.php on line 6
    宝怡 作者 2019-08-07 22:13:31
  • 回复 test2.php最后还有一行: echo (new test1)->getName();
    宝怡 作者 2019-08-07 22:14:56
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号