I have the following code:
$this->load->library('dummyLib');
$this->dummyLib->dummyLibFunction();
(I am using a PHP-Framework that works like that)
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
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()
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. So, there's only one option here - find a function by provided name ( CONSTANT_NAME
) and execute it.
So, the answer is: yes , you should use a variable in this case.
Also, there's another option with using call_user_func_
methods:
function callMe()
{
echo '123';
}
define ('CALL_ME', 'callMe');
call_user_func(CALL_ME);
// yep, this works: https://3v4l.org/tbRrr
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.