Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling PHP language constructs using a string

I wanna buffer some content. The way how the content is fetched depends, that's why I added a type parameter to my buffer function to define whether to include or to echo the source.

PHP

<?php

function bufferContent($source, $type = 'include') {
  ob_start();
  $type($source);
  return ob_get_clean();
}

echo bufferContent('<html>test</html>', 'echo');

?>

Output

Fatal error: Call to undefined function echo() in #### on line 5

Why's that? Isn't it possible to call a standard PHP function like echo() or include() by a string variable?

Edit: Changed question slightly to make it more suitable to the answers.

like image 357
Ben Avatar asked Apr 28 '26 09:04

Ben


1 Answers

echo is not a function : it is a language construct -- and, as such, it cannot be called this way.

A possibility for you would be to define a function, that would itself call echo -- and use your function when calling bufferContent :

function my_echo($str) {
    echo $str;
}
echo bufferContent('<html>test</html>', 'my_echo');

A a reference, quoting [the manual page of `echo`][1] :

Note: Because this is a language construct and not a function, it cannot be called using variable functions

like image 112
Pascal MARTIN Avatar answered Apr 29 '26 22:04

Pascal MARTIN



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!