从脚本中实例化类时遇到麻烦。我的代码基本上是这样的:
ConstAttributes.php位于服务器上,例如/var/www/abc/def/
<?php
namespace My\Path;
class ConstAttributes {
const ONE = "some";
const TWO = "text";
const THREE = "here";
}
?>
index.php位于服务器上其他位置,例如/var/www/xyz/123/
<?php
use My\Path\ConstAttributes;
$aInst = new My\Path\ConstAttributes();
?>
我也尝试过:
use My\Path\ConstAttributes;
$aInst = new ConstAttributes();
,但结果相同。我正在apache2服务器上对此进行实时测试。 apache ist配置为指向索引页面。当我刷新页面时,它只是空白-没有任何内容。创建实例后出现的所有内容都不会显示。好像脚本把自己挂在了那里。当我做这样的事情时:
use My\Path\ConstAttributes;
//$aInst = new My\Path\ConstAttributes();
echo 'test';
我确实得到了预期的回显消息。
这样做的目的是访问index.php脚本中的const
变量。在尝试实例化该类之前,我尝试过ConstAttributes::ONE
,但是那就像在实例化该类时所做的那样快死了。
我已经在Google上搜索了很多,但无法解决问题。帮助将不胜感激。
谢谢。
答案 0 :(得分:0)
如果尝试在php类中使用常量,则php引擎将引发异常“注意:使用未定义的常量ONE-在...中假定为'ONE'”。要变通解决此问题,可以定义并使用全局常数。请在此处查看演示代码。
//
<?php
/*
* mypath\ConstAttributes.php
*/
namespace MyPath2;
//
define("ONE1", "One1");
const TWO2 = "Two2";
define("SIX", "Six6");
const SEVEN = "Seven7";
define("EIGHT", "Eight8");
const ONE = "some";
const TWO22 = "text2";
define("TWO", "text");
const THREE = "here";
//
/**
* Description of ConstAttributes
*
* @author B
*/
class ConstAttributes {
var $one = ONE;
var $two = TWO;
var $three = THREE;
var $two2 = TWO2;
var $four = "four4";
var $five = "five5";
var $seven = SEVEN ;
var $eight = EIGHT ;
function MyOne(){
return ONE1;
}
function MyTwo(){
return $this->two2;
}
function MyThree(){
return $this->three;
}
function MyFour(){
return $this->four;
}
function MySeven(){
return $this->seven;
}
}
//
完成此操作后,就可以正常使用index.php了。
//
<!DOCTYPE html>
<!--
index.php
-->
<html>
<head>
<meta charset="UTF-8">
<title>Demo</title>
</head>
<body>
<?php
use MyPath2\ConstAttributes;
include 'mypath\ConstAttributes.php';
$aInst = new ConstAttributes();
echo gettype($aInst)."<br>";
echo $aInst->MyOne()."<br>";
echo $aInst->MyTwo()."<br>";
echo $aInst->MyFour()."<br>";
echo $aInst->five."<br>";
echo SIX."<br>";
echo $aInst->MySeven()."<br>";
echo $aInst->eight."<br>";
echo "////////////////////////<br>";
echo $aInst->one."<br>";
echo TWO."<br>";
echo $aInst->MyThree()."<br>";
echo "///////////////////////////<br>";
//echo TWO22."<br>";
echo "///////////////////////////<br>";
?>
</body>
</html>
//
测试的输出如下:
//////////////////output////////////
// object
// One1
// Two2
// four4
// five5
// Six6
// Seven7
// Eight8
////////////////////////
// some
// text
// here
///////////////////////////
///////////////////////////
//
享受!