[英]“unexpected T_PAAMAYIM_NEKUDOTAYIM” on one computer but not another with PHP 5
[英]Unexpected T_PAAMAYIM_NEKUDOTAYIM in PHP 5.2.x
我很难理解为什么在以下代码中出现Unexpected T_PAAMAYIM_NEKUDOTAYIM
错误,这对我来说似乎完全有效...
class xpto
{
public static $id = null;
public function __construct()
{
}
public static function getMyID()
{
return self::$id;
}
}
function instance($xpto = null)
{
static $result = null;
if (is_null($result) === true)
{
$result = new xpto();
}
if (is_object($result) === true)
{
$result::$id = strval($xpto);
}
return $result;
}
在PHP 5.3+中的输出:
echo var_dump(instance()->getMyID()) . "\n"; // null
echo var_dump(instance('dev')->getMyID()) . "\n"; // dev
echo var_dump(instance('prod')->getMyID()) . "\n"; // prod
echo var_dump(instance()->getMyID()) . "\n"; // null
但是在以前的版本中,我无法执行$result::$id = strval($xpto);
,有人知道为什么吗?
有没有解决此问题的方法?
错误的原因仅仅是<
5.3中不支持该语法。
但是,如果尝试访问静态变量$ id,则语法为:
$result::id
如果确实需要访问静态变量变量,则一种解决方法是使用反射:
$class = new ReflectionClass($xpto);
echo $class->setStaticPropertyValue ('id', strval($xpto));
看完键盘后:
if (is_object($result) === true)
{
$result::id = strval($xpto);
}
... 应该
if (is_object($result) === true)
{
$result::$id = strval($xpto);
}
我在一个新的粘贴中对此进行了更正,该错误仍然存在...只是让您知道演示代码中的问题。
编辑
在有关static
关键字的PHP文档页面上,
从PHP 5.3.0开始,可以使用变量来引用类。 变量的值不能是关键字(例如self,parent和static)。
不幸的是,没有提供任何关于为什么以前版本的详细信息,我也看不到注释中提供的解决方法。
由于该类是静态的,因此您应该能够直接更改该属性:
function instance($xpto = null)
{
static $result = null;
if (is_null($result) === true)
{
$result = new xpto();
}
if (is_object($result) === true)
{
xpto::$id = strval($xpto)
}
return $result;
}
如果使用,它可能会在某些服务器(PHP VERSION ??)上发生: if (empty(NAME_OF_A_CONSTANT)) ...
PHP版本5.3.3,在该代码上没有任何错误。
输出:
string(0)“” string(3)“ dev” string(4)“ prod” string(0)“”
您的错误可能出在其他地方。 请仔细检查报告的行号。
我是通过引用来到这里的: PHP 5.2中的语法错误,其中Chandresh提到了您的链接:一种解决PHP 5.2的方法是:
class Sample{
public static $name;
public function __construct(){
self::$name = "User 1";
}
}
$sample = new Sample();
$class = 'Sample';
$name = 'name';
$val_name = "";
$str = '$class::$$name';
eval("\$val_name = \"$str\";");
//echo $val_name."<br>";
eval("\$name = $val_name;");
echo $name;
忽略是否已解决。 谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.