Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> PHP

Truyền tham số từ mảng vào constructor PHP


Reflection API có thể dùng để truyền tham số từ mảng vào constructor.

ReflectionClass::newInstanceArgs

Dòng trên tạo instance class mới từ các tham số cho trước:

public ReflectionClass::newInstanceArgs ([ array $args ] ) : object

Nó tạo instance mới của class khi tham số truyền cho constructor. args là các tham số cần truyền cho constructor của class.

Ví dụ

<?php 
    $my_class = new ReflectionClass('ReflectionFunction'); 
    $my_instance = $my_class->newInstanceArgs(array('substr')); 
    var_dump($my_instance); 
?>

Kết quả

object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" }