简体   繁体   中英

What's the best way to use php variables in html attributes?

As to using a PHP variable as a HTML attribute, what would be the best way? Is there even a difference?

The (basic) way I see it there are three methods, which all output the same result:

Method one:

<?php
    $img = 'img/img.png';
?>
    <img src="<?php echo $img ?>">

Method two:

<?php
    $img = 'img/img.png';

    echo '<img src="' . $img . '">';
?>

Method three:

<?php
    $img = 'img/img.png';

    echo '<img src="';
    echo $img;
    echo '">';
?>

With my basic knowledge of PHP, I assume the last one is for sure not the way to go. But is there a major difference between the first two?

Like the comments suggest, this will very much be based on opinion and personal preference.

I find (opinion) it's good to separate the concern of PHP logic and displaying to the screen though, so would go for something like this. The reason being, that if you're working in a team, someone that knows HTML + CSS can edit the view without knowing PHP. You can look up templating such as Smarty, but PHP itself is a great template engine. :

in the logic side of things (separate PHP file) you would have something like:

<?php
//get the image source from the database.  (logic)
$imgsrc = db_returnvalue("select imgvalue FROM products where imgid = '$id'");
?>

then in the template (view) side of things you just inject the logic values...

<!-- primarily HTML -->
<div>
    <img src="<?php echo $imgsrc;?>" />
</div>

All the web designer needs to learn is how to echo and maybe do simple loops in PHP.

The other reason I've evolved to prefer this way, is that your HTML looks like HTML in a text editor. Otherwise, if it's echo'd out in PHP, it becomes hard to read since the text editor can't read the HTML, since it's in a big string and won't have it tabbed correctly.

Hope it gives you an alternative idea, and a reason how it might benefit anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM