Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 101: variable vs function

I'm creating a global file to hold items that will be re-used throughout my website. What are the differences between these two lines of code? Is one "better" than the other?

This:

$logo = "img/mainlogo.jpg";

vs this:

function logo() {
   echo "img/mainlogo.jpg";
}
like image 486
Adam Avatar asked Feb 18 '23 05:02

Adam


2 Answers

You should code clear and readable and split in the html and php. The performance profit is not significant...

<?php
...
$logo = "img/mainlogo.jpg";
...
?>
...
<img src="<?= $logo ?>" alt="logo"> 
...
like image 170
BlackCat Avatar answered Feb 26 '23 17:02

BlackCat


Of the two options you posted, the function is the better choice. But, to be brutally honest, this sort of thing is exactly what constants are for:

defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo.jpg');

suppose you're working on a site that has to support multiple languages, then you can simply use the same trick:

defined('CLIENT_LOCALE')  || define('CLIENT_LOCATE',$whereverYouGetThisFrom);
defined('MAIN_LOGO') || define('MAIN_LOGO','img/mainlogo_'.CLIENT_LOCALE.'.jpg');
//if language is EN, mainlogo_EN.jpg will be used, if lang is ES, mainlogo_ES.jpg, etc...

Besides, a constant, once defined cannot be redefined (clue is in the name, of course). Also: since PHP still has a lot of C-stuff going under the bonnet, and you've tagged this question performance, it might interest you that constants are much like C's macro's, which are a lot faster than regular function calls, or even C++ inline functions (even if they were indeed compiled as inline functions).

Anyway, if you have a ton of these things you want to centralize, either think of creating a couple of ini files for your project, and parse them into some sort of global object

like image 28
Elias Van Ootegem Avatar answered Feb 26 '23 16:02

Elias Van Ootegem