Frage

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

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top