PHP features that you rarely use - Part 1

Once you get past the basics of PHP, you might want to check these lesser known PHP language features!

Posted by Darwin Biler on February 3, 2019
This article is written for seasoned PHP developers who been using PHP for everyday work and would be interested to see some feature they often oversee.

Circumventing illegal variable names using Variable variables

$name = '123'; /* 123 is your variable name, this would normally be invalid. */ 
$$name = '456'; // the  $$ here says that this is a variable variable - a variable whose name is contained in another variable. 
echo ${'123'}; // Finally, using curly braces you can output '456'

The difference between isset() and empty() functions

  • isset() will return true if a variable exists and has a value other than NULL
  • empty() will return true if the value passed to it is NULL, or any value that can be coerced to false, including an empty string, an empty array, integer zero, and string “0”

functions and constants will fallback to global namespace if its not present in current namespace

namespace foo;
strlen("foo"); // falls back to \strlen();
but if you attempt to use a class or interface, it wont:
namespace foo;
$now = new DateTime(); // this will cause error, since it will try to use \foo\Datetime
the above DateTime will only work if you prefix it with "\" (e.g \DateTime), indicating it is in the global scope (it will not automatically fallback)

Using namespaced item dynamically

You can strore the fully qualified namespace of a class inside a string, then use that to instantiate it.
$class = "\Foo\Bar\MyString";
$string = new $class("this is a param passed to constructor");

All functions in PHP always return a value

the following function will return the value of NULL, even if you did not specified any return statement.
function donothing(){}

Variadics

this allow you to explicitly denote a function as accepting a variable length argument list
function f($arg1, ...$args) {    
	
	$count = strlen ($arg1);    
	
	foreach ($args as $arg) {       
 		$count += strlen($arg);    
	} 

	return $count;
}
the 3 dots in the arguments says that the function can have more than 1 arguments

Argument unpacking or “splat.”

Argument unpacking works the opposite of the way variadics does, allowing you to unpack an array-like data structure into an argument list when calling a function or method.
	$args = ["World", "Universe", "Hello World"];
	echo str_replace(...$args); // Returns "Hello Universe"

Using curly braces to interpolate variable names inside a string

$me = 'Darwin';
$names = array('Biler', 'Jones', 'Jackson');
echo "There cannot be more than two {$me}s!"; // w/o the curly braces, the interpreter will look for $mes variable
echo "Citation: {$names[1]}[1987]"; // w/o the curly braces, php interpreter will treat [1987] as an array index

String Dereferencing

You can treat a string as an array, here we can use dereferencing to get the item in index 1.
echo "abcdef"[1]; // Outputs 'b'	

Dangling/Trailing Comma

you can leave a comma after the last item in the array
 $points = [
     1,
     5,
     7,
     9,
 ];	
or in function call
unset(
    $one,
    $two,
    $three,
);	

Grouped use declarations

if you have Class1 and Class2 inside the \Foo\Bar namespace, you can declare them in one statement like:
use Foo\Bar\{
    Class1,
    Class2,
};

Using list in foreach

$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sql = "SELECT user_first, user_last, last_login FROM users";
$result = $pdo->query($sql);
foreach ($result as list($first, $last, $last_login)) {
   echo "$last, $first - Last Login: $last_login" . PHP_EOL;
}

I hope those snippets can be quite useful for you. That should be the first batch!

Soon - the part 2...