Convert PHP code into Ruby!
RSS icon Email icon Home icon
  • call_user_func

    Posted on March 27th, 2010 RubyLove No comments

    The call_user_func() function in PHP calls a user defined function as specified by the first parameter. You can also use call_user_func() to call an instance method of an object by using an array(instance, methodName) parameter as follows:

    PHP

    class User{
      private $name = null;
     
      public function __construct($name){
         $this->name = $name;
      }
     
      public function getName(){
        return $this->name;
      }
    }
     
    $user = new User('Shaymol');
    echo call_user_func( array($user, 'getName') );
     
    // => Shaymol

    To get same behavior in Ruby we can call the send() method of an object as follows:

    Ruby

    # define a user class
    class User
      attr_accessor :name
     
      def initialize(name)
         @name = name.capitalize
      end
     
    end
     
    # create a user object
    user = User.new('Shaymol')
     
    # this is similar to user.name, and in PHP similar to call_user_func($obj, 'methodName');
    puts user.send(:name)
     
    # => Shaymol

    This page was contributed by Shaymol. Thanks!