Ray Lee | 李宗叡
Learn or Die
Published in
2 min readApr 27, 2024

--

# Typed Class Constants

8.2 之前,儘管 Interface 定義 constant 的型別,但在 child class 卻可以 overwrite 這個型別

<?php
interface I {
const TEST = "Test"; // We may naively assume that the TEST constant is always a string
}

class Foo implements I {
const TEST = []; // But it may be an array...
}

class Bar extends Foo {
const TEST = null; // Or null
}

從 8.3 開始, child class constant 可以 overwrite constant,但型別不可變

<?php
interface I {
const string TEST = E::TEST; // I::TEST is a string as well
}

class Foo implements I {
use T;

const string TEST = E::TEST; // Foo::TEST must also be a string
}

class Bar extends Foo {
const string TEST = "Test2"; // Bar::TEST must also be a string, but the value can change
}

// Error example

// Fatal error: Cannot use array as value for class constant
// Foo::PHP of type string
class Buzz implements I {
const string PHP = [];
}

# The json_validate() function

PHP 8.2 之前,若要驗證 JSON 是否合法,需要使用以下的方式

<?php
json_decode(json: '{"foo": "bar}', flags: JSON_THROW_ON_ERROR);

// JsonException Control character error, possibly incorrectly encoded.

PHP 8.3 開始可以使用以下的方式來驗證

// Valid
json_validate('{"framework": "Laravel"}'); // true

// Invalid
json_validate('{"framework": "Laravel}'); // false

json_last_error_msg(); // Control character error, possibly incorrectly encoded
json_last_error(); // 3

# Dynamic class constant fetch

8.3 開始,dynamically 取得 constant 的方式有變

class Framework {
const NAME = 'Laravel';
}

$name = 'NAME';

// You could achieve this with the constant() function
constant(Framework::class . '::' . $name); // Laravel

// This following is a syntax error in >=v8.2.0
echo Framework::{$name};
// ParseError syntax error, unexpected token ";", expecting "(".

# Fallback value for environment variables in INI files

8.3 開始,可在 php.ini 文件當中定義參數的 fallback value

[www]
listen = localhost:${DRUPAL_FPM_PORT:-9000}

# Randomizer Additions

8.3 新增的 method 可以取得指定 string 的 random bytes,如下範例

$randomizer = new \Random\Randomizer();

printf(
"%s.example.com",
$randomizer->getBytesFromString('abcdefghijklmnopqrstuvwxyz0123456789', 16)
);

// 3zsw04eiubcf82jd.example.com


// Generate a random code for multi-factor authentication
$randomizer = new \Random\Randomizer(new \Random\Engine\Secure());

echo implode('-', str_split($randomizer->getBytesFromString('0123456789', 20), 5));

// 11551-80418-27047-42075

# 參考來源

--

--

Ray Lee | 李宗叡
Learn or Die

It's Ray. I do both backend and frontend, but more focus on backend. I like coding, and would like to see the whole picture of a product.