大多数情况下,您可以避免使用回显变量,但有时这些回显字符串包含行终止符或引号(也称为字符串分隔符)。您可以测试并再次测试,但您只是必须保护自己免受“恶意”和“不可预测”的输入。在这个答案中,我同时使用了单引号和双引号
您可以str_replace 或urlencode 您的字符串,这将解决您的问题,但老实说……json_encode 到底有什么问题?它非常适合服务器 客户端数据,就像您正在使用的那样:
var someVal = JSON.parse(<?= json_encode(array('data' => $someVar));?>).data;
所有需要转义的字符都将被转义...工作完成,并使用“本机”PHP 函数。
更新:
正如下面的 cmets 所示,由于范围问题,这可能是 PHP 错误。与其在类中声明变量,不如声明一个属性:
class Foo
{
public $theProperty = null;
public function __construct($argument = null)
{
$this->theProperty = $argument;//assign a variable, passed to a method to a property
$someVar = 123;//this variable, along with $argument is GC'ed when this method returns
}
}
//end of class
$instance = new Foo('Value of property');
echo $instance->theProperty;//echoes "value of property"
$anotherInstance = new Foo();//use default value
if ($anotherInstance->theProperty === null)
{//is true
echo 'the property is null, default value';
$anotherInstance->theProperty = 'Change a property';
}
基本上就是这样。我不知道你是如何使用你的视图脚本的,所以下面的代码可能不适用于你的情况(这是你可以在 Zend Framework 中的控制器中做的):
public function someAction()
{
$instance = new Foo('Foobar');
$this->view->passedInstance = $instance;//pass the instance to the view
}
然后,在您的视图脚本中,您将执行以下操作:
var someVal = JSON.parse('<?= json_encode(array('data' => $this->passedInstance->someProperty)); ?>').data;
但为了让我的回答适用于您的情况,我必须看看您是如何渲染视图的……您使用的是框架吗?你使用的是经典的 MVC 模式,还是视图脚本只是你include 的东西?