Type casting
/**
* Type casting means converting a variable from one type to another.
* The name of the type is written in parentheses.
*/
$arr = ["a" => 1, "b" => 2];
$obj = (object) $arr; // Look here
echo $obj->b; // 2
Type hinting
/**
* Type hinting (or type declarations) is used to specify the expected type.
*/
declare(strict_types=1);
function add(int $a, int $b): int
{
return $a + $b;
}
try {
echo add (1, "2");
} catch (TypeError $e) {
echo $e->getMessage();
}
/**
* add(): Argument #2 ($b) must be of type int, string given
*/
Union types
/**
* Prior to PHP 8.0 you could only declare a single type for
* properties, parameters, and return types.
*
* A union type is a collection of different datatypes in the same memory location.
* With PHP 8.2 you can use union type in class property declaration.
*
* To separate each datatype use pipe |
* The ?string is equivalent with string|null
*/
class Test
{
private int|float $value = 10; // Look Here
private ?string $name;
public function set(int|float $n, ?string $str): void
{
$this->value = $n;
$this->name = $str;
}
public function getValue(): int|float
{
return $this->value;
}
public function getName(): ?string
{
return $this->name;
}
}
$a = new Test();
$b = new Test();
$a->set(10, "one");
$b->set(5.5, NULL);
echo $a->getValue() . " " . $a->getName() . PHP_EOL; // 10 one
echo $b->getValue() . " " . $b->getName() . PHP_EOL; // 5.5
Object type
/**
* The default object in PHP is of stdClass type.
* The stdClass type has no properties, methods or parent.
*/
$A = (object) array(); // OR
$A = new stdClass();
$A->x = 3;
$A->y = 4;
print_r($A);
/**
* stdClass Object ([x] => 3, [y] => 4)
*/
Questions and answers:
Clink on Option to Answer
1. How do you type cast a variable to integer?
- a) $a = (int) $a;
- b) $a = (int $a);
2. Can you use union types in php?
- a) no
- b) yes, starting with PHP 8.2
3. Which one is a union type declaration?
- a) int|float $x = 10;
- b) int $x = 20;
4. What is a union type?
- a) A collection of different datatypes in the same memory location
- b) An if/else condition
5. What ?string is equivalent to?
- a) string|null
- b) not a string
6. Is there a difference between type casting and hinting?
- a) yes, hinting is about what type you expect
- b) yes, casting is about php automatic type conversion