# Syntax, Variables, Types and strict_types — PHP

Source: https://www.skillbyai.com/en/php/f-basics

> Write PHP with variables, scalar types, constants and strict typing.

## The basics, done the modern way

PHP code lives between `<?php` tags; files that contain only PHP should omit the closing `?>` to avoid accidental whitespace output. Variables start with **`$`** and are created by assignment. PHP has scalar types (`int`, `float`, `string`, `bool`), compound types (`array`, `object`, `callable`, `iterable`) and special ones (`null`, `resource`). PHP is dynamically typed, but you should add **type declarations** to parameters, return values and properties. By default PHP **coerces** scalar arguments (passing `"5"` to an `int` parameter becomes `5`); adding **`declare(strict_types=1);`** at the top of a file makes calls from that file throw a `TypeError` instead, which catches bugs early. Compare with **`===`** (identical: same type and value) rather than `==` (loose comparison with type juggling); PHP 8 made `0 == "abc"` false, but loose comparison still has surprises. Constants are defined with `const NAME = value;`. Strings in single quotes are literal, while double quotes interpolate variables (`"Hello {$user->name}"`). The `??` (null coalescing) and `??=` operators supply defaults for missing values.

## Types, comparisons and null handling

Strict typing turns silent coercion into an error you can fix.

```php
<?php
declare(strict_types=1);

const GST_RATE = 0.18;

function priceWithGst(float $price): float
{
    return round($price * (1 + GST_RATE), 2);
}

echo priceWithGst(100.0), PHP_EOL;     // 118
// priceWithGst("100");               // TypeError under strict_types

var_dump("1" == "01");    // true  (numeric strings compared as numbers)
var_dump("1" === "01");   // false (different strings)
var_dump(0 == "abc");     // false in PHP 8 (was true in PHP 7)

$config = ['timeout' => 30];
$retries = $config['retries'] ?? 3;     // default when the key is missing
$config['region'] ??= 'ap-south-1';    // assign only if not set
```

## Use === by default

Loose `==` comparisons convert types in ways that are easy to forget, especially with numeric strings, null and booleans. Use `===` and `!==` unless you deliberately want conversion.

**Quiz:** What does declare(strict_types=1) change?

- [ ] It makes all variables constant
- [ ] It disables arrays
- [x] Calls from that file to typed functions throw TypeError instead of silently coercing scalar types
- [ ] It enables the JIT

*Answer:* Calls from that file to typed functions throw TypeError instead of silently coercing scalar types. strict_types disables scalar coercion for calls made in that file.
