Skip to content

Instantly share code, notes, and snippets.

@alan-ps
Last active August 3, 2019 13:44
Show Gist options
  • Save alan-ps/b08b719b698a1f98ba97d7fa3a1ef83d to your computer and use it in GitHub Desktop.
Save alan-ps/b08b719b698a1f98ba97d7fa3a1ef83d to your computer and use it in GitHub Desktop.

Alternate Null Type Syntax

<?php

function myFunc(?MyObject $myObj) {
  echo 'Hello World!';
}

myFunc(null); // this is allowed
myFunc(); // this produces a fatal error: Too few arguments

Variadics

<?php
  
function myFunc($required, $optional = NULL, ...$variadicParams) {
  print_r($variadicParams);
}
  
myFunc(1, 2, 3, 4); // array([0] => 3, [1] => 4);

Return Type Declarations

<?php

function getFullName(string $firstName, string $lastName): string {
  return 100;
}

$name = getFullName('Serhii', 'Puchkovskyi');
echo gettype($name); // string

Return Void

If the function is going to return NULL, we can specify that it will return "void":

<?php

function myFunc(): void {
  echo 'Hello World!';
}

sayWorld(); // Hello World!

Lambda and Closure

<?php

$lambda = function($a, $b) {
  echo $a + $b;
};

$lambda(2, 3); // 5
echo (int) is_callable($lambda); // 1
echo get_class($lambda); // Closure

$string = 'Hello World!';
$closure = function() use ($string) {
  echo $string;
};
$closure(); // Hello World!
Early and Late Binding
<?php

$a = 'Some string';
// Early binding (default).
$b = function() use ($a) {
  echo $a;
};

$a = 'Hello World!';
$b(); // Some string
<?php

$a = 'Some string';
// Late binding (reference).
$b = function() use (&$a) {
  echo $a;
};

$a = 'Hello World!';
$b(); // Hello World!
Binding Closures to Scopes
<?php

class test {
  protected $text = 'Default text';

  public function showText() {
    return function () { return $this->text; };
  }
}

class testA extends test {}
class testB {
  protected $text = 'Some another text';
}
  
$testA = new testA();
$testB = new testB();
  
$test1 = $testA->showText()->bindTo($testB);
$test2 = Closure::bind($testA->showText(), $testB);
  
print_r($test1); // Some another text
print_r($test2); // Some another text
Self-Executing Closures
<?php
// Displays 'Hello World!'.
(function() {
  echo 'Hello World!';
})();
Helpful links:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment