30 tips of code PHP - Types

razielrodrigues

Raziel Rodrigues

Posted on March 28, 2024

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 
END; 
# 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];
var_dump($arrayUnpacking);

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

# Will add the same data here because of the pointer
var_dump($appointed);
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!';
    exit;
}

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

try {
    willContinue();
} 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.

💖 💪 🙅 🚩
razielrodrigues
Raziel Rodrigues

Posted on March 28, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

30 tips of code PHP - Types
php 30 tips of code PHP - Types

March 28, 2024