<?php
function myFunc(?MyObject $myObj) {
echo 'Hello World!';
}
myFunc(null); // this is allowed
myFunc(); // this produces a fatal error: Too few arguments
<?php
function myFunc($required, $optional = NULL, ...$variadicParams) {
print_r($variadicParams);
}
myFunc(1, 2, 3, 4); // array([0] => 3, [1] => 4);
<?php
function getFullName(string $firstName, string $lastName): string {
return 100;
}
$name = getFullName('Serhii', 'Puchkovskyi');
echo gettype($name); // string
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!
<?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!
<?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!
<?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
<?php
// Displays 'Hello World!'.
(function() {
echo 'Hello World!';
})();