PHP - 您可以为变量分配成员函数吗?

时间:2014-10-18 03:51:21

标签: php

在PHP5中,变量可以作为函数1进行评估,例如:

function myFunc() {
   echo "whatever";
}

$callableFunction = 'myFunc';

$callableFunction(); // executes myFunc()

是否有任何语法可以将对象成员函数分配给变量,例如:

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

3 个答案:

答案 0 :(得分:7)

有一种方法,但对于PHP 5.4及以上版本......

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

$obj = new Myclass();

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

$ref();

嗯......实际上它也适用于静态,只需按名称使用引用..

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

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

$ref();

对于非静态的,这种表示法也适用。它创建了一个类的临时实例。所以,这就是你需要的,只需要你需要php 5.4及以上版本)

答案 1 :(得分:2)

上面的PHP 5.4解决方案很好。如果您需要PHP 5.3,我认为您可以比匿名函数方法做得更好,但您可以将其包装到一个与PHP 5.4方法非常相似的函数中:

function buildCallable($obj, $function)
{
    return function () use ($obj, $function) {
        $args = func_get_args();
        return call_user_func_array(array($obj, $function), $args);
    };
}

//example
class MyClass
{
    public function add($x, $y)
    {
        return $x + $y;
    }

    public static function multiply($x, $y)
    {
        return $x * $y;
    }
}

//non-static methods
$callable = buildCallable(new MyClass(), 'add');
echo $callable(32, 10);

//static methods
$callable = buildCallable('MyClass', 'multiply');
echo $callable(21, 2);

这适用于任何(公开可见)方法的任意数量的参数。

答案 2 :(得分:-1)

@PressingOnAlways,您可以通过以下方式执行此操作:

<?php
class Foo
{
    function Variable()
    {
        $name = 'Bar';
        $this->$name(); // This calls the Bar() method
    }

    function Bar()
    {
        echo "This is Bar";
    }
}

$foo = new Foo();
$funcname = "Variable";
$foo->$funcname();  // This calls $foo->Variable()

?>

这是标准的程序,即使你可以改变$ funcname变量,这样他们就可以轻松调用类的不同功能。

您可以访问this

如果您还有任何问题,请与我们联系。