DEV Community

Raziel Rodrigues
Raziel Rodrigues

Posted on

30 tips of code PHP - Types

PHP is a loosely typed language, which means PHP can convert strings into integers or act in other types of conversions automatically. However, this is one of the singularities of PHP types. Let's dig into some edge uses of types.

All types in PHP

  • null
  • bool (0, 1, true, false)
  • int
  • float (floating-point number)
  • string
  • array
  • object
  • callable (functions)
  • resource (External libraries)

Digging into

  • Heredoc printing

Did you know that PHP has heredoc as a way to print things? That's how it works!

echo <<<END 
a b c \n 
# Then the indentation will persist when printing 
# You can also pass variables, functions, and other interactions inside the string or even save the result in a variable 
Enter fullscreen mode Exit fullscreen mode
  • Powers of array

Arrays are one of the most powerful types in PHP. Let's learn some cool stuff to do with arrays.

# You can create an array like this
$array = new ArrayObject(); 

# Destructuring an array
$destruct = ['test', 'key'];
[$test, $key] = $destruct;
$destructAssociative = ['name'=> 'Raziel'];
['name' => $myName] = $destructAssociative;
var_dump($test, $key, $destructAssociative);

# Spread operator (similar to JavaScript)
$arrayUnpacking = [...$destructAssociative, ...$destruct];

# Pointers
$point = [1,2,3];
$appointed = &$point;
$point[] = 'hello';

# Will add the same data here because of the pointer
Enter fullscreen mode Exit fullscreen mode
  • Enum

Don't need to create constants inside classes anymore.

enum Suit {
    case Suit;
Enter fullscreen mode Exit fullscreen mode
  • Declare types

An easter egg about declare(strict_types=1).

# File with declare
function sum(int $a, int $b)
    return $a + $b;
Enter fullscreen mode Exit fullscreen mode
  • The never return type

This one is such a gem. The 'never' return type ignores the throw, exit, or die function. When 'never' is defined as a return type, even if you call 'exit' inside the function, the system will continue instead of stopping.

function neverSay(): never
    echo 'Nobody can stop me!';

function willContinue(): never
    throw new Exception('No way!');

try {
} catch (Exception $th) {
    echo $th->getMessage();
Enter fullscreen mode Exit fullscreen mode

That's all! I hope those tips can help you in your career and in your daily tasks. See you in my next articles.

Top comments (0)