Real Dreams
Real Dreams

Reputation: 18010

Undefined variables in PHP template

I use PHP as a template language in my view layer, Is it possible to make the following a little cleaner and more concise?

//in temp.phtlm
<?= (isset($user['name'])) ? $user['name'] : null; ?> 

Unfortunately, we can not even define a function for that:

// as you know yet a notice is generated when calling a function with an undefined parameter
function echo($var)
{
        return (isset($var)) ? $var : null;
}

Upvotes: 1

Views: 600

Answers (4)

Real Dreams
Real Dreams

Reputation: 18010

Using @ operator is the shortest alternative.

<?= @$user['name']; ?> 

Since PHP 7 you can also use the ?? operator.

<?= $user['name'] ?? null; ?> 

Which does exactly what the @ operator does, though a bit longer.

Upvotes: 0

孙锡源
孙锡源

Reputation: 11

You can use it so you won't be prompted that the variable is undefined:

$args = $args ?? null;

Upvotes: 1

Nemoden
Nemoden

Reputation: 9056

//in temp.phtlm
<?=$var?>

//in whatever_your_script_name.php
$template->var = isset($var) ? htmlentities(whatever(convert(encode($var)))) : '';
$template->render('temp.phtml');

Upvotes: 2

Damien Overeem
Damien Overeem

Reputation: 4529

There is no short hand method to do that quicker, no. Any other method would throw an error if $var did not exist at that point.

Depending on your structure/templating system you could use a class to store your var's and use the magic methods __get, __set, __isset, __unset to call your variables. Those methods could then just return null if the var didnt exist. This would require quite a change in your code though. You can find the manual about magic methods here: http://php.net/manual/en/language.oop5.magic.php

As for your original code, i would write it like this:

<?php echo ( isset($var) ? $var : null ); ?> 

Upvotes: 2

Related Questions