PHP short way to echo string?

4.1k views Asked by At

In PHP we echo strings this way :

echo 'string';

But i saw PHP frameworks like Laravel and scripts echo strings using Curly Brackets :

{string}

How i can do that without using any PHP framework?

It's not necessary to use Curly Brackets if there is other way to short echo!

I prefer code examples.

4

There are 4 answers

3
baao On

You can short echo by

<?= $variable; ?> when you open a new php tag

or you use, as described in your question a framework such as laravel - that's pretty much it

What you can do, but I'm not really sure if it's a good idea - write a function like:

function x($string) {
    echo $string;
}

x('Test');  // will output Test
4
Jite On

PHP has a few methods to print strings, such as (but not limited to) print, and echo or just shorthand <?= "str" ?>.
The bracket print that you ask about from laravel is not per say in php.
That is from a template engine called Blade.

So the {} way of printing stuff is not possible in php.
You will have to stick to the standard ways or use a template engine!

4
Ryan On

The short answer is you can't do that with PHP. PHP provides language constructs to output to standard output, etc. PHP doesn't provide a pre-processor. Most template frameworks are a pre-processor meaning that they convert your {<STRING>} into an echo $x statement.

So either create your own template framework, or stick to PHP's API.

0
Amr SubZero On

After researching i found a Template Engine called Smarty that allows me to echo using Curly Brackets

First i created 2 files index.php , template.html

Then i moved the folder /libs that i downloaded from the template page to my script directory

and in my index.php i required the Smarty.class file

require_once "libs/Smarty.class.php";

then i called the Smarty class :

$smarty = new Smarty;

after that i pushed the variable :

$smarty ->assign("name",'Amr');

and i displayed the template file index.html

$smarty ->display("template.html");

at the end i wrote in the index.html <p>{$name}</p> and it outputted : Amr