Redefining constant in PHP



Take care when you use ($this) in your anonymous functions (closures) – it will be copied

Anonymous functions1 (closures) in PHP 5.3 are cool. Awesome is when you can use2 any variable with it. With PHP 5.4 you can even use $this.

The problem with use is that it is making the value available in the current scope by copying2 it, thus not modifying it upwards the chain. To over come this, simply pass by reference1.

$anon = function(){
    // Some fancy execution right here

$otherRandomVar = 5;
$anon = function() use ($otherRandomVar) {
    // $otherRandomVar will be made available in $anon() by copy
    // In this case it is not modifying its value in the global scope
    $otherRandomVar = 8915 + 945;

echo $otherRandomVar; // 5

$randomVar = 'abc';
$anonFuncRightHere = function() use (&$randomVar) {
    // Passing by reference will solve your issue
    $randomVar = 'cba';

echo $randomVar; // cba

MAMP fine tuning: enable XDEBUG and turn on error reporting

MAMP addresses developers, so I can’t really understand why these are turned off by default:

  1. Enable XDEBUG:
    • nano/vim /Applications/MAMP/bin/php/php5.6.10/conf/php.ini
      (Note: you may be using another version of PHP)
    • Search for “xdebug”
    • Delete the semicolon
    • Restart MAMP (or just Apache)
    • Test with phpinfo(); It should show as compiled
  2. Enable PHP Error Reporting: 
    • nano/vim /Applications/MAMP/bin/php/php5.6.10/conf/php.ini – same file as above
      (Note: replace php5.6.10 with your PHP version)
    • Search for “display_errors”
    • Change from “off” to “on”
    • Restart MAMP or just Apache

Happy debugging!

PHP search array in array

Sometimes PHP can be such an old fart. Ever wanted to search for $haystack in an $array which is an array in another array without writing more than one line of code?

One liner for a simple $array – classic:

$bool = in_array($anything, $array);

One liner for multidimensional array for PHP >= 5.5.0

$array = array_search($anything, array_column($array, 'column_key'));

One liner for multidimensional array for PHP < 5.5.0:

You’ll have to use Composer, good luck! :-)