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

倖福魔咒の 提交于 2019-12-01 18:44:52

问题


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

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 yields a labeled input box with the value displayed as Array[user_login]. I can assign the array to separate variables and get the output I'm looking for, but this seems like an unnecessary waste. PHP 5.3.5


回答1:


Wrap your array variable inside curly braces {} like this

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

Here is a nice article on this.

From the article

Unfortunately, PHP doesn’t provide any direct means for calling functions or outputting expression results in HEREDOC strings. The problem here is that, unless the thing in the curly braces starts with a dollar sign, it can’t be recognized by PHP as something to be replaced.



来源:https://stackoverflow.com/questions/18885968/how-to-display-the-value-of-an-array-element-or-object-property-in-php-heredoc-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!