简体   繁体   English

在PHP中使用常量调用具有该名称的函数

[英]Using constant to call a function with that name in PHP

I have the following code: 我有以下代码:

$this->load->library('dummyLib');
$this->dummyLib->dummyLibFunction();

(I am using a PHP-Framework that works like that) (我使用的是这样的PHP框架)

Now I want to be able to change the different libraries depending on a constant that I have defined priviously: 现在,我希望能够根据我私下定义的常量来更改不同的库:

defined('LIB') OR define('LIB', 'dummy');

Which I can use like $myLibrary = LIB 我可以像$myLibrary = LIB

As I have to load that library in different locations I want my code to automatically adjust to that constant. 由于必须在不同位置加载该库,因此我希望我的代码自动调整为该常数。 I know that function calls are possible with variables like this: 我知道可以使用这样的变量进行函数调用:

$myFunctionNameInThisVariable = 'test';
$this->$myFunctionNameInThisVariable();

This will call $this->test() 这将调用$this->test()

Can I do the same with constants? 我可以对常量做同样的事情吗? Or do I always have to use an additional variable? 还是我总是必须使用其他变量?

To answer your question, let's compare function calls: 为了回答您的问题,让我们比较一下函数调用:

a normal function call is: 正常的函数调用是:

$this->functionName();

a function call with defined constant is 具有定义的常量的函数调用是

$this->CONSTANT_NAME();

As in php functions' names are case insensitive , php cannot understand what you want to do - call a function CONSTANT_NAME or replace constant CONSTANT_NAME with is real value. 由于php函数的名称不区分大小写 ,因此php无法理解您要执行的操作-调用函数CONSTANT_NAME或将常数CONSTANT_NAME替换为实际值。 So, there's only one option here - find a function by provided name ( CONSTANT_NAME ) and execute it. 因此,这里只有一个选项-按提供的名称CONSTANT_NAME )查找一个函数并执行它。

So, the answer is: yes , you should use a variable in this case. 因此,答案是: 是的 ,在这种情况下,您应该使用一个变量。

Also, there's another option with using call_user_func_ methods: 另外,还有一个使用call_user_func_方法的选项:

function callMe()
{
    echo '123';
}
define ('CALL_ME', 'callMe');
call_user_func(CALL_ME);
// yep, this works: https://3v4l.org/tbRrr

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM