Navigation Menu

Skip to content

Commit

Permalink
ObjectMixin: added support for getting public methods as Closure
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Jul 15, 2012
1 parent 185cfce commit f4b9762
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
8 changes: 8 additions & 0 deletions Nette/common/ObjectMixin.php
Expand Up @@ -149,6 +149,14 @@ public static function & get($_this, $name)
self::$methods[$class] = array_flip(get_class_methods($class));
}

// public method as closure getter
if (isset(self::$methods[$class][$name])) {
$val = function() use ($_this, $name) {
return call_user_func_array(array($_this, $name), func_get_args());
};
return $val;
}

// property getter support
$name[0] = $name[0] & "\xDF"; // case-sensitive checking, capitalize first character
$m = 'get' . $name;
Expand Down
58 changes: 58 additions & 0 deletions tests/Nette/common/Object.methodGetter.phpt
@@ -0,0 +1,58 @@
<?php

/**
* Test: Nette\Object closure properties.
*
* @author David Grudl
* @package Nette
* @subpackage UnitTests
*/




require __DIR__ . '/../bootstrap.php';



class TestClass extends Nette\Object
{
private $id;

function __construct($id = NULL)
{
$this->id = $id;
}

public function publicMethod($a, $b)
{
return "$this->id $a $b";
}

protected function protectedMethod()
{
}

private function privateMethod()
{
}

}



$obj1 = new TestClass(1);
$method = $obj1->publicMethod;
Assert::same( "1 2 3", $method(2, 3) );


Assert::throws(function() {
$obj = new TestClass;
$method = $obj->protectedMethod;
}, 'Nette\MemberAccessException', 'Cannot read an undeclared property TestClass::$protectedMethod.');


Assert::throws(function() {
$obj = new TestClass;
$method = $obj->privateMethod;
}, 'Nette\MemberAccessException', 'Cannot read an undeclared property TestClass::$privateMethod.');

1 comment on commit f4b9762

@fprochazka
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Boner.

Please sign in to comment.