0

trying to run class method in class method callback.

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();
} );

ERROR:

Warning: Undefined variable $use in C:\xampp\htdocs\class\index.php on line 9

Fatal error: Uncaught Error: Call to a member function showUserAge() on null in C:\xampp\htdocs\class\index.php:9 Stack trace: #0 [internal function]: {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} thrown in C:\xampp\htdocs\class\index.php on line 9

Thank you!

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • I hope this shall help. https://stackoverflow.com/questions/708341/can-i-include-a-function-inside-of-another-function Thank you! – Buddhsen Tripathi Jun 29 '21 at 16:05
  • You need to read up on variable scopes: https://www.php.net/manual/en/language.variables.scope.php (the variable `$use` isn't accessible inside the anonymous function's scope). – M. Eriksson Jun 29 '21 at 16:06
  • Thank you for your help! I will look into those. –  Jun 29 '21 at 16:06

2 Answers2

1

Unlike javascript, PHP doesn't automatically include outside variables in lambda functions - you will need to explicitly list the variables you want to allow using the "use" syntax.

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

For example:

$user = new User();

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

Daniel Von Fange
  • 857
  • 9
  • 10
0

Try doing

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" );
dokgu
  • 4,957
  • 3
  • 39
  • 77