Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Mixed Pseudo Type ใน PHP 8

Mixed type ใน PHP 8 เป็น union type ในตัวใหม่ Mixed type เทียบเท่ากับ array|bool|callable|int|float การผสมผสานประเภทไม่ได้คล้ายกับการละเว้นประเภทโดยสมบูรณ์

นั่นหมายถึง โปรแกรมเมอร์เพียงแค่ลืมเขียน

บางครั้งโปรแกรมเมอร์ชอบละเว้นบางประเภทเฉพาะเพื่อรักษาความเข้ากันได้กับรุ่นเก่า

Mixed type ใน PHP 8 สามารถรับประเภทของพรอเพอร์ตี้/ค่าคืน/พารามิเตอร์ได้ทุกประเภท เราสามารถพูดได้ว่ามันรวมถึง null, callable, resource, ทุกคลาสอ็อบเจกต์ หรือทุก scalar types ใน PHP Mixed type เทียบเท่ากับ Union type

int|float|bool|string|null|array|object|callable|resource

ตัวอย่าง: Mixed Type ใน PHP 8

<?php 
class Student{ 
    public mixed $studentProperty; 
    public function emp(mixed $emp): mixed {} 
} ?>
  • ใน PHP 8 Mixed เป็น pseudo/virtual type แทนหลายประเภทที่ PHP จัดการได้ หมายความว่าเราไม่สามารถ cast ตัวแปรเป็น mixed ได้ เพราะไม่มีเหตุผล

$foo = (mixed) $bar;

หมายเหตุ: ฟังก์ชัน gettype() และ get_debug_type() ไม่มีทางคืนค่า mixed เป็นประเภทของตัวแปร

  • เราไม่สามารถใช้ mixed ใน union กับประเภทอื่นได้

function(mixed|FooClass $bar): int|mixed {}

หมายเหตุ: ในโค้ดด้านบน union type ทั้งสองไม่ได้รับอนุญาตและจะให้ fatal error

ผลลัพธ์

Fatal error: Type mixed can only be used as a standalone type in C:\xampp\htdocs\gud.php on line 2

ตัวอย่าง: โค้ดโปรแกรม PHP 8 ใช้ Mixed Type

<?php 
function debug_function(mixed ...$data){ 
    print_r($data); 
} 
debug_function(10, 'string', []); 
?>

ผลลัพธ์

Array ( 
    [0] => 10 
    [1] => string 
    [2] => Array 
    ( 
    ) 
)