g-kari / PHP8.5がくるらしい

Created Mon, 17 Nov 2025 10:34:30 +0000 Modified Mon, 17 Nov 2025 11:11:09 +0000

PHP8.5がくるらしい

TL;DR

これを読みなさい

https://stitcher.io/blog/new-in-php-85

パイプ演算子

$input = ' Some kind of string. ';

$output = strtolower(
    str_replace(['.', '/', '…'], '',
        str_replace(' ', '-',
            trim($input)
        )
    )
);

$output = $input 
    |> trim(...)
    |> (fn (string $string) => str_replace(' ', '-', $string))
    |> (fn (string $string) => str_replace(['.', '/', '…'], '', $string))
    |> strtolower(...);

おしゃれ ただ結果記述長くなる場合がありそうだし、phpの->methodみたいに呼出すのをヘルパーとかでやるのはどうなんだろ 好みが分かれそう

より詳細

Clone with

final class Book
{
    public function __construct(
        public string $title,
        public string $description,
    ) {}
    
    public function withTitle(string $title): self
    {
        return clone($this, [
            'title' => $title,
        ]);
    }
}

🙄

new selfとくらべてなにがいんだろう

プロパティを直接更新する関数が、更新されたプロパティをオブジェクトのマジックメソッドに渡す関数よりも優れていると 考える主な理由は、パブリックプロパティを持つオブジェクトを、オブジェクトの支援なしに外部から変更されたプロパティで複製できるためです。さらに、クラス内での変更は、メソッドに集中させるのではなく、適切なメソッドに局所化できます。 clone()__clone()__clone()

<?php
 
$cloned  = clone $object ; 
foreach  ( $withProperties  as  $key  =>  $value )  { 
    $cloned -> { $key }  =  $value ; 
} 
return  $cloned ;

パブリックreadonlyプロパティは、クラス内からクローン作成中に変更できます。

<?php
 
class Foo {
    public readonly int $pub;
 
    public function withPub($newPub) {
        return clone($this, ["pub" => $newPub]);
    }
}
 
$foo = new Foo();
// object(Foo)#2 (1) { ["pub"]=> int(5) }
[var_dump](http://www.php.net/var_dump)($foo->withPub(5));

インスタンス化に依存しなくてもプロパティを変更できるのか。

かつ、スコープは維持されるから、外から直接cloneでプロパティ弄ろうとしてエラーになるらしい。 いいね。

#[\NoDiscard]

😑

<?php
 
/**
 * Processes all the given items and returns an array with the results of the
 * operation for each item. `null` indicates success and an Exception indicates
 * an error. The keys of the result array match the keys of the $items array.
 * 
 * @param array<string> $items
 * @return array<null|Exception>
 */
#[\NoDiscard("as processing might fail for individual items")]
function bulk_process([array](http://www.php.net/array) $items): [array](http://www.php.net/array) {
	$results = [];
 
	foreach ($items as $key => $item) {
		if (\random_int(0, 9999) < 9999) {
			// Pretend to do something useful with $item,
			// which will succeed in 99.99% of cases.
			echo "Processing {$item}", PHP_EOL;
			$error = null;
		} else {
			$error = new \Exception("Failed to process {$item}.");
		}
 
		$results[$key] = $error;
	}
 
	return $results;
}

Golangとかだと適切に返り値処理しないと怒られるから、それみたいな感じかな?

(void) キャストで警告を無視できるらしい。 より硬い言語へ

クロージャの