How to display the value of an array element or object property in PHP Heredoc syntax

I'm having trouble displaying the value of an array inside the heredoc input field. Here is the code snippet:

class Snippet{ protected $_user; protected $_class; protected $_messages; public function __construct(){ $this->_user = $this->_class = NULL; $this->createUser(); } public function createUser(){ $keys = array('user_login','user_email'); $this->_user = $this->_class = array_fill_keys($keys, ''); } public function userErrors(){ //by default give the login field autofocus $_class['user_login'] = 'autofocus'; } public function getForm(){ return <<<HTML <form id='test' action='' method='post'> $this->_messages <fieldset> <legend>Testing Heredoc</legend> <ol> <li> <label for='user_login'>Username</label> <input id='user_login' name='user_login' type='text' placeholder='Login name' value=$this->_user[user_login] $this->_class[user_login]> </li> </ol> </fieldset> </form> HTML; } } 

My output gives a marked input field with a value displayed as Array[user_login] . I can assign an array to separate the variables and get the result I'm looking for, but this seems like an unnecessary waste. PHP 5.3.5

+4
source share
1 answer

Wrap an array variable inside curly braces {} like this

 value="{$this->_user['user_login']} {$this->_class['user_login']}" 

Here is a good article about it.

From the article

Unfortunately, PHP does not provide any direct means to call a function or output the results of an expression to HEREDOC strings. the problem is that if an item in curly braces does not start with a dollar sign, it cannot be recognized by PHP as a substitute.

+10
source

Source: https://habr.com/ru/post/1502939/


All Articles