Kurz gesagt, Sie können Folgendes abbilden
- __Aufruf eines method_missing-Aufrufs mit Argumenten
- __set zu einem method_missing-Aufruf, bei dem der Name der Methode mit '=' endet
- __get zu einem method_missing-Aufruf ohne Argumente
__Aufruf
php
class MethodTest {
public function __call($name, $arguments) {
echo "Calling object method '$name' with " . implode(', ', $arguments) . "\n";
}
}
$obj = new MethodTest;
$obj->runTest('arg1', 'arg2');
Rubinrot
class MethodTest
def method_missing(name, *arguments)
puts "Calling object method '#{name}' with #{arguments.join(', ')}"
end
end
obj = MethodTest.new
obj.runTest('arg1', 'arg2')
__set und __get
php
class PropertyTest {
// Location for overloaded data.
private $data = array();
public function __set($name, $value) {
echo "Setting '$name' to '$value'\n";
$this->data[$name] = $value;
}
public function __get($name) {
echo "Getting '$name'\n";
if (array_key_exists($name, $this->data)) {
return $this->data[$name];
}
}
}
$obj = new PropertyTest;
$obj->a = 1;
echo $obj->a . "\n";
Rubinrot
class PropertyTest
# Location for overloaded data.
attr_reader :data
def initialize
@data = {}
end
def method_missing(name, *arguments)
value = arguments[0]
name = name.to_s
# if the method's name ends with '='
if name[-1, 1] == "="
method_name = name[0..-2]
puts "Setting '#{method_name}' to '#{value}'"
@data[method_name] = value
else
puts "Getting '#{name}'"
@data[name]
end
end
end
obj = PropertyTest.new
obj.a = 1 # it's like calling "a=" method : obj.a=(1)
puts obj.a