【问题标题】:How to call method inside method in php如何在php中调用方法内部的方法
【发布时间】: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 中抛出

谢谢!

【问题讨论】:

标签: php


【解决方案1】:

与 javascript 不同,PHP 不会自动在 lambda 函数中包含外部变量 - 您需要使用“使用”语法明确列出您希望允许的变量。

https://www.php.net/manual/en/functions.anonymous.php

例如:

$user = new User();

$user->showUserName( 'ARIF', function () use ($user) {
    $user->showUserAge();
} );

【讨论】:

  • 感谢您的帮助!我会检查的。
【解决方案2】:

尝试做

class User {
    public function showUserAge( $age = 10 ) {
        echo $age;
    }
    public function showUserName( $name = 'arif', $fn ) {
        echo $name;
        
        if( method_exists( $this, $fn ) ) {
            $this->$fn();
        }
    }
}

$use = new User();

$use->showUserName( 'ARIF', "showUserAge" );

【讨论】:

    猜你喜欢
    • 2021-03-29
    • 2022-11-21
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多