将PHP函数与HTML属性连接并且不能将类型对象用作数组

将PHP函数与HTML属性连接并且不能将类型对象用作数组

问题描述:

I have 2 questions

<< 1.>>

I have php print code like this.

echo '<label class="control-label" for="'.to_string($dt->name_comp).'">'.$dt->name_comp.'</label>';

to_string is function that produce My Name to my_name, and it works, clear, with $dt->name_comp produce the value from database. So.. that syntax must be html syntax like it: <label class="control-label" for="my_name">Name Component</label>

I wanna ask, why code above can't work? Why my_name not get into for?

I've tried this way:

echo '<label class="control-label" for="'. <?php to_string($dt->name_comp); ?>.'">'.$dt->name_comp.'</label>';

But, it same. The result is always like this: <label class="control-label" for=" ">Name Component</label> when I check it in firebug. So my_name appear outside form, doesn't enter into the form. Wonder why..

This is to_string() function:

function to_string($string) {
  $string = preg_replace('/[\'"]/', '', $string);
  $string = preg_replace('/[^a-zA-Z0-9]+/', '_', $string);
  $string = trim($string, '_');
  $string = strtolower($string);
  echo $string; 
}

<< 2>>

I have code for textinput like this:

echo '<input type="text" name="'.to_string($dt->name_comp).'" id="'.to_string($dt->name_comp).'" placeholder="'.$dt->name_comp.'"  value="'.$dt['/name_comp/'].'">';

But, there is an error: Fatal error cannot use object of type workspace_mockup_2\Models\Component as array What should I enter there? Need some advice.. Thank's.

The last line of to_string() should be:

return $string;

When you do:

echo "something".to_string(something_else);

The sequence of events is this:

  1. to_string(something_else) is called.
  2. to_string echoes the string it creates.
  3. to_string returns undefined.
  4. "something" is concatenated with undefined, which results in "something".
  5. "something" is echoed.

This is why to_string's result is echoes outside the label, because it is echoed in step 2, while the label is echoed in step 5.