• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 214
  • Last Modified:

calling a function through object

Hi all,

<?php
class MyClass {
    function myFunc() {
        print 'This is my function in myclass';
    }
}
?>

<?php
$myArr = array('theFunc' => 'myFunc()');
$theObj = new MyClass();
$theObj->$myArr['theFunc'];
?>

I know that the third line of this code won't work. So I need an alternate or better way of doing it.

Either the function name or the entire call should be in the array. Like:
(1) $myArr = array('theFunc' => 'myFunc()');       OR
(2) $myArr = array('theFunc' => '$theObj->myFunc()');

The actual scenario is much more complex which I can't explain it here, but a solution for this code should solve my problem.

Thank you all.
0
sangeetha
Asked:
sangeetha
2 Solutions
 
TeRReFCommented:
I think this should work:
<?php
class MyClass {
    function myFunc() {
        print 'This is my function in myclass';
    }
}

$myArr = array('theFunc' => 'myFunc');
$theObj = new MyClass();
$theObj->$myArr['theFunc']();
?>
0
 
ixtiCommented:
Hope this is clear and will help you:

<?php
class MyClass
{
    function MyClass()
    {
    }
   
    function MyFirstFunc()
    {
        echo "Sample\n";
        return true;
    }
   
    function MySecondFunc()
    {
        $a = array("pineapple", 1 => "oranges");
        return $a;
    }
   
    function MyThirdFunc($firstParam)
    {
        return $firstParam * 10;
    }
   
    function __function($functionName, $params = array())
    {
        $functionName = str_replace("()", "", $functionName);
        return call_user_func_array(array($this, $functionName), $params);
    }
}

$funcs  = array('first' => 'MyFirstFunc', 'second' => 'MySecondFunc', 'third' => 'MyThirdFunc');

$obj    = new MyClass();

var_dump($obj->__function($funcs['first']));
// Result:
// Sample
// bool(true)

var_dump($obj->__function($funcs['second']));
// Result:
// array(2) {
//   [0]=>
//   string(9) "pineapple"
//   [1]=>
//   string(7) "oranges"
// }

var_dump($obj->__function($funcs['third'], array(100)));
// Result:
// int(1000)
?>
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now