8

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

3
  • 4
    Do yourself (or whoever is going to maintain that code) a favor and separate your business logic from the presentation. HTML output intermingled with PHP logic is a quagmire, heredoc or not. Commented Sep 19, 2013 at 4:03
  • Try using PHP's templating instead of HEREDOC, it would be simpler. Commented Sep 19, 2013 at 4:05
  • too right you are... separated Commented Sep 19, 2013 at 4:36

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.