【发布时间】:2021-06-29 15:59:55
【问题描述】:
试图在类方法回调中运行类方法。
class.php
<?php
namespace user;
class User {
public function showUserAge( $age = 10 ) {
echo $age;
}
public function showUserName( $name = 'arif', $fn ) {
echo $name;
call_user_func( $fn );
}
}
index.php
<?php
use user\User;
require './class.php';
$use = new User();
$use->showUserName( 'ARIF', function () {
$use->showUserAge();
} );
错误:
警告:第 9 行 C:\xampp\htdocs\class\index.php 中未定义的变量 $use
致命错误:未捕获的错误:在 C:\xampp\htdocs\class\index.php:9 中调用成员函数 showUserAge() on null 堆栈跟踪:#0 [内部函数]:{closure}() # 1 C:\xampp\htdocs\class\class.php(9): call_user_func(Object(Closure)) #2 C:\xampp\htdocs\class\index.php(10): user\User->showUserName(' ARIF', Object(Closure)) #3 {main} 在第 9 行的 C:\xampp\htdocs\class\index.php 中抛出
谢谢!
【问题讨论】:
-
我希望这会有所帮助。 stackoverflow.com/questions/708341/…谢谢!
-
您需要阅读变量作用域:php.net/manual/en/language.variables.scope.php(变量
$use在匿名函数的作用域内无法访问)。 -
感谢您的帮助!我会调查这些。
标签: php