PHP conditional statement and self-calculation

Is this something like OK in PHP?

$foo = $_GET['foo'];
$foo = empty($foo) || !custom_is_valid($foo) ? 'default' : $foo;

Are there any cleaner alternatives to this? I mainly try to avoid additional table calls.

+3
source share
5 answers

As you will see, if you turn it on error_reporting(E_ALL), this is not the best way to do this. PHP basically wants you to do

$foo = empty($_GET['foo']) || !custom_is_valid($_GET['foo']) ? 'default' : $_GET['foo'];
+2
source

Does custom_is_valid () check for an empty variable? Since the ability to remove empty () and "or not" will greatly improve this code.

+3
source

:

$foo = 'default';
if (array_key_exists('foo', $_GET) and custom_is_valid($_GET['foo'])) {
    $foo = $_GET['foo'];
}

, :)

0

, , , , , .

In addition, I like to use the following function, so I do not receive a warning about access to nonexistent array keys when running E_STRICT:

function GetVar($var, $default = '') {
  $value = $default;
  if(isset($_GET[$var])) {
    $value = $_GET[$var];
  }
  return $value;
}

function custom_clean($value, $default = '') {
  ... validation logic or return $default ...
}

$foo = custom_clean(GetVar('foo'), 'default');
0
source

The class here will make your life a lot easier.

<?php

class ParamHelper
{
  protected $source;

  public function __construct( array $source )
  {
    $this->source = $source;
  }

  public function get( $key, $default=null, $validationCallback=null )
  {
    if ( isset( $this->source[$key] ) && !empty( $this->source[$key] ) )
    {
      if ( is_null( $validationCallback ) || ( !is_null( $validationCallback ) && call_user_func( $validationCallback, $this->source[$key] ) ) )
      {
        return $this->source[$key];
      }
    }
    return $default;
  }
}

// Just for the demo
function validateUpper( $value )
{
  return ( $value == strtoupper( $value ) );
}

// Mimic some query-string values
$_GET['foo'] = 'bar';
$_GET['bar'] = 'BAZ';
$_GET['lol'] = 'el oh el';

$getHelper = new ParamHelper( $_GET );

echo $getHelper->get( 'foo', 'foo default', 'validateUpper' ), '<br>';
echo $getHelper->get( 'bar', 'bar default', 'validateUpper' ), '<br>';
echo $getHelper->get( 'baz', 'baz default' ), '<br>';
echo $getHelper->get( 'lol' ), '<br>';
echo $getHelper->get( 'rofl' ), '<br>';
0
source

Source: https://habr.com/ru/post/1715558/


All Articles