从服务器上其他位置的脚本实例化类 或者:访问脚本中的 const 变量



我在脚本中实例化类时遇到问题。我的代码基本上看起来像这样:

常量属性.php位于服务器上,例如/var/www/abc/def/

<?php
namespace MyPath;
class ConstAttributes {
const ONE = "some";
const TWO = "text";
const THREE = "here";
}
?>

索引.php位于服务器上的其他位置,例如/var/www/xyz/123/

<?php
use MyPathConstAttributes;
$aInst = new MyPathConstAttributes();
?>

我也试过:

use MyPathConstAttributes;
$aInst = new ConstAttributes();

但结果是一样的。我正在 apache2 服务器上实时测试这个。Apache ist 配置为指向索引页。当我刷新页面时,它只是空白的 - 上面没有任何内容。创建实例后的所有内容根本不显示;似乎剧本把自己挂在那里了。当我做这样的事情时:

use MyPathConstAttributes;
//$aInst = new MyPathConstAttributes();
echo 'test';

我确实按预期收到回声消息。

这样做的重点是访问 index.php 脚本中的const变量。在尝试实例化类之前,我尝试了ConstAttributes::ONE但就像我实例化类时一样,它在那里消亡了。

我现在用谷歌搜索了很多,但无法解决问题。帮助将不胜感激。

提前谢谢。

如果您尝试在 php 类中使用常量,php 引擎会抛出异常"注意:使用未定义的常量 ONE - 假设 'ONE' 在..."。要解决此问题,可以定义和使用全局常量。请在此处查看演示代码。

//
<?php
/*
* mypathConstAttributes.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 MyPath2ConstAttributes;
include 'mypathConstAttributes.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
///////////////////////////
///////////////////////////
//

享受!

最新更新