![](/img/trans.png)
[英]“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.