Cast A Closure To Array

By Saif Eddin Gmati

<?php

class X {
    private $p = 1;
    public $q = 2;
}

$x = new x;
$y = (array) $x;
print_r($y);

/*
Array
(
    [Xp] => 1
    [q] => 2
)
*/

$f = function() {};
print get_class($f);  /// Closure
var_dump((array) $f);

/*
Closure
array(1) {
  [0]=>
  object(Closure)#2 (0) {
  }
}
*/
?>

TIL: (array) $obj will result in array<string, mixed> ( properties key/value pairs ), with the exception if $obj is Closure, where the result would be [$obj].

See Also

PHP Features

Last updated: 14 July 2026