Most of the time, you can get away with echo-ing variables, but sometimes those echoed strings contain line terminators, or quotes (aka string delimiters). You can test, and test again, but you just have to defend yourself against "malicious" and "unpredictable" input. In this very answer I've used both single and double quotes
You can str_replace or urlencode your strings, which would solve your problems, but honestly... what on earth is wrong with json_encode? It's just perfect for Server <-> client data, like you're using:
var someVal = JSON.parse(<?= json_encode(array('data' => $someVar));?>).data;
All chars that need escaping will be escaped... job done, and with a "native" PHP function.
Update:
As the comments below show, this is probably a PHP error, due to a scope issue. Instead of declaring a variable in the class, you should declare a property:
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';
}
This is, basically how it works. I don't know how you're using your view-script, so the code below might not work in your case (It's what you can do in Zend Framework, in the controller):
public function someAction()
{
$instance = new Foo('Foobar');
$this->view->passedInstance = $instance;//pass the instance to the view
}
Then, in your viewscript, you'd do something like this:
var someVal = JSON.parse('<?= json_encode(array('data' => $this->passedInstance->someProperty)); ?>').data;
But in order for my answer to work in your case, I'd have to see how you're rendering the view... are you using a framework? Are you using the classic MVC pattern, or is the view-script just something you include?
$TESTMEhas"things will crash and burn :)