LoginSignup
10
9

More than 5 years have passed since last update.

PHP無名関数のuseに渡された変数をクロージャの外から取得する

Posted at

ReflectionFunction getStaticVariablesで取得できます.
http://php.net/manual/en/class.reflectionfunction.php

<?php
$profile = [
  'name' => 'Isaac Newton',
  'birthday' => '1646-01-04',
];
$closure = function($params) use ($profile) {
  echo "My name is ${$profile['name']}.";
};

$reflection = new ReflectionFunction($closure);
var_dump( $reflection->getStaticVariables() );
  # array(1) {
  #   ["profile"]=>
  #   array(2) {
  #     ["name"]=>
  #     string(12) "Isaac Newton"
  #     ["birthday"]=>
  #     string(10) "1646-01-04"
  #   }
  # }

Environment

$ uname -a
Linux *** 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/issue
CentOS release 6.5 (Final)
Kernel \r on an \m

$ /usr/local/php-5.5.4/bin/php -v
PHP 5.5.4 (cli) (built: Mar 11 2014 11:06:57)
Copyright (c) 1997-2013 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2013 Zend Technologies

$ /usr/local/php-5.6.0/bin/php -v
PHP 5.6.0 (cli) (built: Aug 29 2014 06:35:44)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies
10
9
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
9