Jump to content

php macros?


pnj

Recommended Posts

 

I often find myself writing this to avoid a php warning:

 

$x = (isset ($_GET['foo']) ? $_GET['foo'] : null);

 

Because php triggers a warning on the following if foo is not in the http get:

 

$x = $_GET['foo'];

 

I'd like to put it in a function, something like

function getval($val) { return (isset ($val) ? $val : null; }

 

But of course this doesn't because the call to getval() triggers the warning.

 

I could use eval() and pass a string, but that also seems inelegant.  In C, I would use a #define macro.  Is there any such thing in php?

 

thanks

 

Link to comment
https://forums.phpfreaks.com/topic/63336-php-macros/
Share on other sites

Well this is a step closer...

 

function get_it($type, $val)
{
  if( $type == "get" )
  {
    if( isset($_GET[$val]) ) return $_GET[$val];
    return "";
  }
  else if( $type == "post" )
  {
    if( isset($_POST[$val]) ) return $_POST[$val];
    return "";
  }
  else if( $type == "session" )
  {
    if( isset($_SESSION[$val]) ) return $_SESSION[$val];
    return "";
  }
  else if( $type == "globals" )
  {
    if( isset($GLOBALS[$val]) ) return $GLOBALS[$val];
    return "";
  }
  return "";
}

 

to call it you'd just do: $var = get_it("post", "username");

Link to comment
https://forums.phpfreaks.com/topic/63336-php-macros/#findComment-315884
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.