How do I get the function name inside a function in PHP? - php

Is it possible?
function test()
{
echo "function name is test";
}

The accurate way is to use the __FUNCTION__ predefined magic constant.
Example:
class Test {
function MethodA(){
echo __FUNCTION__;
}
}
Result: MethodA.

You can use the magic constants __METHOD__ (includes the class name) or __FUNCTION__ (just function name) depending on if it's a method or a function... =)

If you are using PHP 5 you can try this:
function a() {
$trace = debug_backtrace();
echo $trace[0]["function"];
}

<?php
class Test {
function MethodA(){
echo __FUNCTION__ ;
}
}
$test = new Test;
echo $test->MethodA();
?>
Result: "MethodA";

Related

PHP/Laravel How to include one function into another?

Is there a way I can include(?) one function into another? For example, the same way we can include files using include function.
Thank you.
<?php
class test{
public function message1(){
$message = 'i am in message1 function';
return $message;
}
public function message2(){
$message = $this->message1();
echo $message;
}
}
Functions can not be "included" like you mean but you can call them and use their returned values to other functions like below.
Now if you try to call the message2 function using something like:
$messageClass = new test();
echo $messageClass->message2();
you will see that the output is the $message from function message1
Do you mean callback function? If so, this is how to use it:
// This is callback function which will passed as argument to another function.
function callbackFunction1 ($str) {
return strtoupper($str);
}
function mainFunction ($offeredCallback, $str) {
echo( "(" . $offeredCallback($str) . ")<br>");
}
mainFunction("callbackFunction1", "foo");
// Output "(foo)".
// If you want to use Variable Function, define it like this:
$callbackFunction2 = function ($str) {
return strtoupper($str);
};
mainFunction($callbackFunction2, "bar");
// Output "(bar)".
About Variable Function, see Anonymous Function.

Using a variable as class name

I have the following:
User::model()->exists($someParamsHere);
Is there a way to make the class name 'User' dynamic? So something like this:
$className::model()->exists($someParamsHere);
But that doesn't seem to work.
I also read something about the ReflectionClass, but i'm not really sure how to use it.
I tried this, but off course the model() method is never called this way:
$reflectionMethod = new ReflectionMethod($className, 'exists');
$reflectionMethod->invoke(null, $someParamsHere);
$className::model() works with PHP 5.3 and above, if I'm not mistaken. A workaround is to use CActiveRecord::model($className). See the documentation for CActiveRecord.model().
In PHP >= 5.3 works fine:
<?php
class Foo {
static function Bar() {
return "Bar";
}
static function getFoo() {
return new static();
}
function getBar() {
return static::Bar();
}
}
$class = "Foo";
print $class::Bar() . "\n";
print $class::getFoo()->Bar() . "\n";
Result:
Bar
Bar

PHP use class function on sub-functions

i have test class with one function , after including that i can use this class function with included pages but i cant use this function on included page's functions, for example:
testClass.php:
class test
{
public function alert_test( $message )
{
return $message;
}
}
including class:
in this using class i dont have problem
text.php:
<?php
include 'testClass.php';
$t= new test;
echo alert_test('HELLO WORLD');
?>
but i cant use alert_test function with this method:
<?php
include 'testClass.php';
$t= new test;
function test1 ( $message )
{
echo alert_test('HELLO WORLD');
/*
OR
echo $t->alert_test('HELLO WORLD');
*/
}
?>
i want to use test class in sub-functions
What about echo $t->alert_test('HELLO WORLD');? You have to 'tell' PHP where he has to find that function, in this case in $t which is an instance of the test class.
<?php
include 'testClass.php';
function test1 ( $message )
{
$t = new test;
echo $t->alert_test('HELLO WORLD');
}
?>
You should pass the instance ($t) to your function, i.e:
<?php
class test
{
public function alert_test( $message )
{
return $message;
}
}
$t = new test;
function test1 ( $message, $t )
{
echo $t->alert_test('HELLO WORLD');
}
As an alternative (better IMHO) you could declare your function as static, so that you don't even need to instantiate the test class, i.e:
class Message {
static function alert($message) {
echo $message;
}
}
function test_alert($msg) {
Message::alert($msg);
}
test_alert('hello world');
You should "have problem" even in your first example, because alert_test() is an instance function of your test class.
You have to invoke instance methods as:
$instance -> method( $params );
So:
$t -> alert_test();
But local functions [as your test1] should not rely on global objects: pass them as a function argument, if you need.
You can use closures:
$t = new test;
function test1($message) use ($t) {
$t->test_alert($message);
}

php convert string to method call

<?php
$str = "getList";
//now by doing something to $str i need to call getList() method any sugesstions
function getList(){
echo "get list called";
}
?>
Use the call_user_func() function to call the function by name.
This feature is known as Variable functions, here is an example from php.net:
<?php
function foo() {
echo "In foo()<br />\n";
}
function bar($arg = '')
{
echo "In bar(); argument was '$arg'.<br />\n";
}
// This is a wrapper function around echo
function echoit($string)
{
echo $string;
}
$func = 'foo';
$func(); // This calls foo()
$func = 'bar';
$func('test'); // This calls bar()
$func = 'echoit';
$func('test'); // This calls echoit()
?>
More Info:
http://php.net/manual/en/functions.variable-functions.php
You can use the variable as a function name. This will execute getList():
$str();
However, stuff like this is mostly a symptom of a design problem. Care to elaborate what you need this for?

Calling a changing function name on an object with PHP : how?

How would I do something like this :
class Test
{
public function test($methodName) {
$this->$methodName;
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
Maybe I should just pass a parameter "TYPE" and use a "IF statement" but I'm just curious! :)
And what if the "dynamic function name" has one or more parameters?
UPDATE : Thanks everyone! :)
UPDATE #2 - Answer :
class Test
{
public function testOut($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->testOut("a");
$testObj->testOut("b");
The problem with the class is that there was a method named "Test" (the same as the class name)... I changed it and it worked.
class Test
{
public function test($methodName) {
$this->$methodName();
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a");
$testObj->test("b");
Check out call_user_func() - it should do what you want.
Documentation here
call_user_func allows you to do things like this.
For example,
funcname = 'a';
call_user_func(array($testObj, $funcname));
The other alternative is to use variable methods
For example,
$funcname = 'a';
$testObj->$funcname();
If you have a "dynamic function name" with more than one parameter, you can use call_user_func_array, like this:
//in class context..
//$parameters can be an array like array(1,2)
call_user_func_array(array($this, $methodName), $parameters);
The reason you would want to use call_user_func_array instead of call_user_func is that you can pass the parameters the function takes as an array, instead of just as additional parameters, thus allowing you to easily have a variable number of arguments.
Following your particular example and use case, the only way to achieve this exactly:
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
would be to use eval():
class Test
{
public function test($methodName) {
eval($methodName);
}
private function a() {
echo("a");
}
private function b() {
echo("b");
}
}
$testObj = new Test();
$testObj->test("a()");
$testObj->test("b()");
Others pointed out a solution using call_user_func() and rightly so. Also evidently, is faster than using eval() for function calls. Read this:
http://nz.php.net/manual/en/function.call-user-func.php#64415

Categories