SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Evangelist Alchemist's Avatar
    Join Date
    Aug 2006
    Posts
    412
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    calling functions through a variable

    Hello,

    quick question: is it possible in PHP to call a function using a variable this way:

    PHP Code:

    $var 
    'validate_email';
    Check($var);

    $var 'validate_user';
    Check($var);

    function 
    Check($var)  {

    //dynamically call the functions without using switch


    }

    function 
    validate_email() 

     
    //do something 
    }

    function 
    validate_user() 

     
    //do something 

    thanks

  2. #2
    SitePoint Evangelist Alchemist's Avatar
    Join Date
    Aug 2006
    Posts
    412
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

  3. #3
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, of course
    PHP Code:
    $foo 'printf';
    $foo("bar"); 
    see also call_user_func

  4. #4
    SitePoint Evangelist Alchemist's Avatar
    Join Date
    Aug 2006
    Posts
    412
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok, I found everything I needed. i'm posting it here in case someone else has the same question:

    if you need to call a function dynamically from within a class just use:

    PHP Code:
    $func 'validate_email';
    $this->{$func}();

    function 
    validate_email() {
    //do something

    no need to use call_user_func

    today I learned something new

  5. #5
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Actually, if you're using single variable, you can omit { } as well:

    PHP Code:
    $someObj->$methodName(args); 
    { } is for complex expressions

    PHP Code:
    $someObj->{ $foo->bar->getMethodName() } (args); 


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •