Duplication of PHP functions isset

I have long used the custom __isset() function, which basically exists only to make the code look better and save input time:

 function __isset(&$aVariable, $aDefault = null) { return isset($aVariable) ? $aVariable : $aDefault; } 

But today I found out that this function actually creates a variable if it does not exist! And this is a huge problem when you check the properties of an array:

 $lArray = ('A', 'B', 'C'); $lValue = __isset($lArray[4], 'D'); print_r($lArray); // Outputs 0=>'A', 1=>'B', 2=>'C', 3=>NULL 

So, I want to duplicate the current isset() function with PHP and modify it to do what I want. The problem is that I cannot find the actual isset() function in the PHP source code ...

Many frameworks use the isset() function, as shown in the first example, and I cannot imagine that I am the first to encounter this problem.

So my questions are:

  • Where can I find the actual PHP isset() function?
  • Where can I find the actual isset() C function (real implementation)?
  • How to change the code to return a value or a specified default value?
+4
source share
3 answers

Why is all this? Remove & , and he:

 function __isset($aVariable, $aDefault = null) { return isset($aVariable) ? $aVariable : $aDefault; } 
+3
source

Check if array key exists before actual comparison with array_key_exist

 $lArray = array('A','B','C'); $LValue = array_key_exists(2, $lArray)?$lArray[2]:'D'; echo $LValue; 

make sure you need to change __isset to special descriptor arrays

0
source

Removing the & alone sign will result in Notice: Undefined offset: 4 in What I think you need to do is remove & and suppress any E_NOTICE error with @ ;

 $lArray = array('A', 'B', 'C'); $lValue = __isset(@$lArray[4], 'D'); // or @__isset($lArray[4], 'D'); var_dump($lValue); var_dump($lArray); function __isset($aVariable, $aDefault = null) { return isset($aVariable) ? $aVariable : $aDefault ; } 

Exit (without E_NOTICE error)

 string 'D' (length=1) array 0 => string 'A' (length=1) 1 => string 'B' (length=1) 2 => string 'C' (length=1) 

Another solution is to use another isset for the dispatcher array and the object

 $lArray = array('A','B','C'); $lValue = __issetComplex($lArray, 4, 'D'); var_dump($lValue); var_dump($lArray); function __issetComplex($mixed, $key, $aDefault = null) { if (is_array($mixed)) return array_key_exists($key, $mixed) ? $mixed[$key] : $aDefault; if (is_object($mixed)) return isset($mixed->key) ? $mixed->key : $aDefault; return $aDefault; } 

Finally, you can simply override the PHP isset function yourself override_function

0
source

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


All Articles