Send an unknown method call: Difference between revisions

From Rosetta Code
Content added Content deleted
m (oops lost section)
(added php)
Line 26: Line 26:
return 42 + $x;
return 42 + $x;
}
}

package main;
package main;
my $name = "foo";
my $name = "foo";
Line 33: Line 33:
=={{header|Perl 6}}==
=={{header|Perl 6}}==
<lang perl6>$object."$methname"(5)</lang>
<lang perl6>$object."$methname"(5)</lang>

=={{header|PHP}}==
<lang php><?php
class Example {
function foo($x) {
return 42 + $x;
}
}

$example = new Example();

$name = 'foo';
echo $example->$name(5), "\n"; // prints "47"

// alternately:
echo call_user_func(array($example, $name), 5), "\n";
?></lang>


=={{header|Python}}==
=={{header|Python}}==

Revision as of 06:29, 28 August 2011

Send an unknown method call is a draft programming task. It is not yet considered ready to be promoted as a complete task, for reasons that should be found in its talk page.

Invoke an object method where the name of the method to be invoked can be generated at run time.

Cf

JavaScript

String literal "foo" may be replaced by any expression resulting in a string <lang javascript>example = new Object; example.foo = function(x) {

   return 42 + x;

};

name = "foo"; example[name](5) # => 47</lang>

Perl

<lang perl>package Example; sub new {

   bless {}

} sub foo {

   my ($self, $x) = @_;
   return 42 + $x;

}

package main; my $name = "foo"; print Example->new->$name(5), "\n"; # prints "47"</lang>

Perl 6

<lang perl6>$object."$methname"(5)</lang>

PHP

<lang php><?php class Example {

 function foo($x) {
   return 42 + $x;
 }

}

$example = new Example();

$name = 'foo'; echo $example->$name(5), "\n"; // prints "47"

// alternately: echo call_user_func(array($example, $name), 5), "\n"; ?></lang>

Python

String literal "foo" may be replaced by any expression resulting in a string <lang python>class Example(object):

    def foo(self, x):
            return 42 + x

name = "foo" getattr(Example(), name)(5) # => 47</lang>

Ruby

<lang ruby>class Example

 def foo
   42
 end
 def bar(arg1, arg2, &block)
   block.call arg1, arg2
 end

end

symbol = :foo Example.new.send symbol # => 42 Example.new.send( :bar, 1, 2 ) { |x,y| x+y } # => 3</lang>