Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Can you assign a member function to a variable? [duplicate]

Tags:

php

In PHP5, variables can be evaluated as functions1 such as:

function myFunc() {
   echo "whatever";
}

$callableFunction = 'myFunc';

$callableFunction(); // executes myFunc()

Is there any syntax for assigning object member functions to a variable such as:

class MyClass {
    function someCall() {
        echo "yay";
    }
}

$class = new MyClass();

// what I would like:
$assignedFunction = $class->someCall; // but I tried and it returns an error

$memberFunc = 'someCall';
$class->$memberFunc(); // I know this is valid, but I want a single variable to be able to be used to call different functions - I don't want to have to know whether it is part of a class or not.

// my current implementation because I don't know how to do it with anonymous functions:
$assignedFunction = function() { return $class->someCall(); } // <- seems lengthy; would be more efficient if I can just assign $class->someCall to the variable somehow?

$assignedFunction(); // I would like this to execute $class->someCall()
like image 924
PressingOnAlways Avatar asked Oct 18 '14 03:10

PressingOnAlways


1 Answers

There is a way, but for php 5.4 and above...

class MyClass {
    function someCall() {
        echo "yay";
    }
}

$obj = new Myclass();

$ref = array($obj, 'someCall');

$ref();

Hm.. actually it works for static too, just use the reference by name..

class MyClass {
    static function someCall2() {
        echo "yay2";
    }
}

$ref = array('MyClass', 'someCall2');

$ref();

And for nonstatic this notation works as well. It creates a temporary instance of the class. So, this is what you need, only you need php 5.4 and above )

like image 190
Cheery Avatar answered Oct 21 '22 21:10

Cheery