Yousuf Memon
Yousuf Memon

Reputation: 4798

Check a variable whether it is set or not "globally" within a function

I'm trying to make a function which will do what the following statements do....

<?php
if(isset($var)){
    echo $var;
}
else {
    echo "";
}
?>

I have done this so far....

<?php
function echo_ifset($dyn_var){
    $var = $dyn_var;
    if(isset($$var)){
        global $$var;
        echo $$var;
    }
}

but its not displaying anything when I run..

echo_ifset('message');
// while message is a defined variable.

Upvotes: 2

Views: 135

Answers (4)

Darkzaelus
Darkzaelus

Reputation: 2095

If you work with a reference, you won't have any problems with warnings (or errrors, my PHP is a little rusty!) if the variable isn't defined:

function echo_ifset(&$var) { 
    if (isset($var)) { 
        echo $var; 
    };
}

Note the & before the $var declaration, this is the reference operator.

Then, you can just call it using:

echo_ifset($message);

This method is also great if you want to define a method to set a default value:

<?php 
function defaultValue(&$var, $default) { 
    if (!isset($var)) { 
        return $default; 
    }

    return $var;
} 
?>

Some extra reading material can be found at: http://www.php.net/manual/en/language.references.pass.php

Upvotes: 4

Stefan Gi
Stefan Gi

Reputation: 450

delete one $ in the if statement:

function echo_ifset($dyn_var){
$var = $dyn_var;
if(isset($var)){
    global $$var;
    echo $$var;
};
}

Upvotes: 0

Hkachhia
Hkachhia

Reputation: 4539

You have pass message as a string so does not display it.

You have passed like echo_ifset($message). if message variable is already define.

Upvotes: 0

Peter Ilfrich
Peter Ilfrich

Reputation: 3816

You need to echo the returned value of your function:

function ifset($dyn_var) {
  if (isset($dyn_var)) {
    return $dyn_var;
  }
  else {
    return "";
  }
}

And then just use:

echo ifset($var);

Upvotes: 0

Related Questions