Use of undefined constant

Hi, working locally using:


$lang = 'en';
<?php if ($lang == en){ ?>
this is english
<?php }; ?>
<?php if ($lang == it){ ?>
this is italian
<?php }; ?>

i get ‘NOTICE: USE OF UNDEFINED CONSTANT EN - ASSUMED ‘EN’ IN’…when using PHP 5.3.0, however when i use version 5.2.2 all seems fine.

What an i doing wrong?..

Thanks in advance

Two things:

  1. if ($lang == en) and if($lang == it)

if they’re strings, they should be encapsulated in either single or double quotes.

any alphanums outside of quotes (and not prefixed by $) are tested to be functions, classes, keywords, and constants. if all of those fail (and i’m probably forgetting a few), PHP assumes they are meant to be strings, throws that E_WARN level error, and moves on.

Encapsulate your strings and you’ll save yourself and the PHP engine the headache :wink:

2: $lang = ‘en’;
this line isnt inside <?php ?>, and wont be interpreted by the PHP engine.

oh and
3: if…if on exclusive condition.
if the lang is en, it wont be it. make your second if an elseif. It’ll save your script having to process the second if condition.

Thanks StarLion…i ‘usually’ have single quotes…but for some reason i didnt include in this example :slight_smile:

With your last point ‘elseif’, i dont just use 2 languages, it actually uses 6…is there a quicker method to display text (or enclosed div content) whilst running through the dynamically generated $lang value?

well the localization templating scheme would work…

your main page:

<?php
require_once('lang/'.$lang.'.php'); //Lot of dots, i know, but bear with me.

echo $text['HELLO'];
?>

lang/en.php


<?php
$text['HELLO'] = "Hello";
//etc, etc, etc

lang/it.php


<?php
$text['HELLO'] = "Bonjorno" //okay i dont speak italian. sue me :P
//etc etc etc

That way your code doesnt need a lot of if/elses.

You could use switch