Closures don't work as class methods? - php

Am I missing something or do closures simply not work as class methods? Take this for instance:
$foo = new stdClass();
$foo->bar = function() {
echo '###';
};
$foo->bar();
Seems to give me an error of "Fatal error: Call to undefined method stdClass::bar() in /blah/blah.php on line X"
Shouldn't this instead invoke the closure that was placed in the "bar" property?

Yes, that is indeed correct.
The only way to call bar is:
$bar = $foo->bar;
$bar();
Sad, but true.
Also worth noting, because of this same effect, there is no $this inside $bar call (unless you pass it as function argument named as $this).
Edit: As nikic pointed out, the value of $this inside the closure is the same value of the scope of when the closure was created.
This may mean that $this might be undefined on two occasions: when the scope was the global PHP scope or when the scope was from a static context. This, however, means that you can in theory feed the correct instance:
class Foo {
public $prop = 'hi';
function test(){
$this->bar = function(){
echo $this->prop;
}
$bar = $this->bar;
$bar();
}
}
$foo = new Foo();
$foo->test();
Also, it seems that with some class magic, you can achieve $this->bar() as well:
class Foo {
// ... other stuff from above ...
public function __call($name, $args){
$closure = $this->$name;
call_user_func_array( $closure, $args ); // *
}
}
[*] Beware that call_user_func_array is very slow.
Oh, and this is strictly for PHP 5.4 only. Before that, there's no $this in closures :)
Also, you can see it in action here.

Methods and fields are completely separate; in fact, you can even have a method and field of the same name:
<?php
class foo{
function bar() { echo "hello\n"; }
}
$object = new foo;
$object->bar = 1;
$object->bar(); // echoes "hello"
?>
This explains why your syntax could not have created a "real" method.

Related

Can't bind callable object closure [duplicate]

Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.
P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class
class Foo {
public $text = 'Hello World!';
public function say() {
echo $this->text;
}
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable(array(new Foo, 'say'));
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
Code below works fine
function say(){
echo $this->text;
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable('say');
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).
So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable.
This means, you have two options to fix your problem:
Bar must be compatible with the type of Foo - so just make Bar
extend from Foo, if possible.
Use unbound functions, like annonymous, static or functions outside of classes.
It is not supported by PHP. However in PHP 7.0 it was kinda possible. Consider this example:
class Foo {
private $baz = 1;
public function baz() {
var_dump('Foo');
var_dump($this->baz);
}
}
class Bar {
public $baz = 2;
public function baz() {
var_dump('Bar');
var_dump($this->baz);
}
}
$fooClass = new ReflectionClass('Foo');
$method = $fooClass->getMethod('baz');
$foo = new Foo;
$bar = new Bar;
$closure = $method->getClosure($foo);
$closure2 = $closure->bindTo($bar);
$closure2();
The output of foregoing code is:
string(3) "Foo"
int(2)
And this means method Foo::baz was called on object $bar and has accessed its $baz property rather than Foo::$baz.
Also, please note that Bar::$baz is public property. If it was private, php would throw Fatal error cannot access private property. This could've be fixed up by changing the scope of closure $closure->bindTo($bar, $bar);, however doing this was already prohibited in php7.0 and would lead to a following warning: Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure().
There's workaround however, which will work for latest versions of php. Laravel created a splendid package called laravel/serializable-closure. What it does is simple - it reads source code of closure in order to serialize it and be able to unserialize it later with all necessary context.
So basically the functionality of unserialized closure remains the same, however it is different from PHP's perspective. PHP doesn't know it was created from class method and therefore allows to bind any $this.
Final variant will look like this:
$callback = [$foo, 'baz'];
$closure = unserialize(
serialize(new SerializableClosure(Closure::fromCallable($callback)))
)->getClosure();
$closure->call($bar);
Please, note that serialization and unserialization are expensive operations, so do not use provided solution unless there's no other solution.

PHP binding method to another class

Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.
P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class
class Foo {
public $text = 'Hello World!';
public function say() {
echo $this->text;
}
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable(array(new Foo, 'say'));
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
Code below works fine
function say(){
echo $this->text;
}
class Bar {
public $text = 'Bye World!';
public function __call($name, $arguments) {
$test = Closure::fromCallable('say');
$res = Closure::bind($test, $this);
return $res();
}
}
$bar = new Bar();
$bar->say();
This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).
So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable.
This means, you have two options to fix your problem:
Bar must be compatible with the type of Foo - so just make Bar
extend from Foo, if possible.
Use unbound functions, like annonymous, static or functions outside of classes.
It is not supported by PHP. However in PHP 7.0 it was kinda possible. Consider this example:
class Foo {
private $baz = 1;
public function baz() {
var_dump('Foo');
var_dump($this->baz);
}
}
class Bar {
public $baz = 2;
public function baz() {
var_dump('Bar');
var_dump($this->baz);
}
}
$fooClass = new ReflectionClass('Foo');
$method = $fooClass->getMethod('baz');
$foo = new Foo;
$bar = new Bar;
$closure = $method->getClosure($foo);
$closure2 = $closure->bindTo($bar);
$closure2();
The output of foregoing code is:
string(3) "Foo"
int(2)
And this means method Foo::baz was called on object $bar and has accessed its $baz property rather than Foo::$baz.
Also, please note that Bar::$baz is public property. If it was private, php would throw Fatal error cannot access private property. This could've be fixed up by changing the scope of closure $closure->bindTo($bar, $bar);, however doing this was already prohibited in php7.0 and would lead to a following warning: Cannot rebind scope of closure created by ReflectionFunctionAbstract::getClosure().
There's workaround however, which will work for latest versions of php. Laravel created a splendid package called laravel/serializable-closure. What it does is simple - it reads source code of closure in order to serialize it and be able to unserialize it later with all necessary context.
So basically the functionality of unserialized closure remains the same, however it is different from PHP's perspective. PHP doesn't know it was created from class method and therefore allows to bind any $this.
Final variant will look like this:
$callback = [$foo, 'baz'];
$closure = unserialize(
serialize(new SerializableClosure(Closure::fromCallable($callback)))
)->getClosure();
$closure->call($bar);
Please, note that serialization and unserialization are expensive operations, so do not use provided solution unless there's no other solution.

static method vs non-static method

Below are the examples of php class code that is static method and non static method.
Example 1:
class A{
//None Static method
function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>";
} else {
echo "\$this is not defined.<br>";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is defined (A)
$this is not defined.
Example 2:
class A{
//Static Method
static function foo(){
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")<br>\n";
} else {
echo "\$this is not defined.<br>\n";
}
}
}
$a = new A();
$a->foo();
A::foo();
//result
$this is not defined.
$this is not defined.
I am trying to figure out what is the difference between these two Classes.
As we can see on the result of the none static method, the "$this" was defined.
But on the other hand the result on the static method was not defined even they were both instantiated.
I am wondering why they have different result since they were both instantiated?
Could you please enlighten me on what is happening on these codes.
Before we go any further: Please, get into the habbit of always specifying the visibility/accessibility of your object's properties and methods. Instead of writing
function foo()
{//php 4 style method
}
Write:
public function foo()
{
//this'll be public
}
protected function bar()
{
//protected, if this class is extended, I'm free to use this method
}
private function foobar()
{
//only for inner workings of this object
}
first off, your first example A::foo will trigger a notice (calling a non-static method statically always does this).
Secondly, in the second example, when calling A::foo(), PHP doesn't create an on-the-fly instance, nor does it call the method in the context of an instance when you called $a->foo() (which will also issue a notice BTW). Statics are, essentially, global functions because, internally, PHP objects are nothing more than a C struct, and methods are just functions that have a pointer to that struct. At least, that's the gist of it, more details here
The main difference (and if used properly benefit) of a static property or method is, that they're shared over all instances and accessible globaly:
class Foo
{
private static $bar = null;
public function __construct($val = 1)
{
self::$bar = $val;
}
public function getBar()
{
return self::$bar;
}
}
$foo = new Foo(123);
$foo->getBar();//returns 123
$bar = new Foo('new value for static');
$foo->getBar();//returns 'new value for static'
As you can see, the static property $bar can't be set on each instance, if its value is changed, the change applies for all instances.
If $bar were public, you wouldn't even need an instance to change the property everywhere:
class Bar
{
public $nonStatic = null;
public static $bar = null;
public function __construct($val = 1)
{
$this->nonStatic = $val;
}
}
$foo = new Bar(123);
$bar = new Bar('foo');
echo $foo->nonStatic, ' != ', $bar->nonStatic;//echoes "123 != foo"
Bar::$bar = 'And the static?';
echo $foo::$bar,' === ', $bar::$bar;// echoes 'And the static? === And the static?'
Look into the factory pattern, and (purely informative) also peek at the Singleton pattern. As far as the Singleton pattern goes: Also google why not to use it. IoC, DI, SOLID are acronyms you'll soon encounter. Read about what they mean and figure out why they're (each in their own way) prime reasons to not go for Singletons
Sometimes you need to use a method but you don't want call class, because some functions in a class called automatically like as __construct, __destruct,... (Magic Methods).
called class:
$a = new A();
$a->foo();
Don't called class: (just ran foo() function)
A::foo();
http://php.net/manual/en/language.oop5.magic.php

PHP: can we access the property without declaration?

<?php
class A
{
public $attribute1;
function operation1()
{
echo 'operation1';
}
}
$a = new A();
$a->attribute3 = 10;
echo $a->attribute3;
when i run above script, It shows: 10
Question:
There is no declaration of attribute3 in class A? why i can still use it $a->attribute3 = 10;?
As #Hamish said ... because that is how PHP works.
Just like you can say:
$a = "hello";
and create a property in a function's scope or in the global scope you can use
$obj->a = "hello";
to create a property in the $obj instance's scope.
If this is undesired behavior you can throw an exception using the __get and __set magic methods.
class A{
public $property1;
public function __get($property){
throw new Exception($property." does not exist in ".__CLASS__);
}
public function __set($property, $value){
throw new Exception($property." does not exist in ".__CLASS__);
}
}
In short: because you can.
PHP lets you define object attributes without declaring them in the class.
It's not an uncommon feature, e.g. python:
class Foo(object):
pass
foo = Foo()
foo.bar = "Hi"
print foo.bar # "Hi"

Classes within classes in PHP

Can you do this in PHP? I've heard conflicting opinions:
Something like:
Class bar {
function a_function () { echo "hi!"; }
}
Class foo {
public $bar;
function __construct() {
$this->bar = new bar();
}
}
$x = new foo();
$x->bar->a_function();
Will this echo "hi!" or not?
Will this echo "hi!" or not?
No
Change this line:
$bar = new bar();
to:
$this->bar = new bar();
to output:
hi!
It's perfectly fine, and I'm not sure why anyone would tell you that you shouldn't be doing it and/or that it can't be done.
Your example won't work because you're assigning new Bar() to a variable and not a property, though.
$this->bar = new Bar();
In a class, you need to prefix all member variables with $this->. So your foo class's constructor should be:
function __construct() {
$this->bar = new bar();
}
Then it should work quite fine...
Yes, you can. The only requirement is that (since you're calling it outside both classes), in
$x->bar->a_function();
both bar is a public property and a_function is a public function. a_function does not have a public modifier, but it's implicit since you specified no access modifier.
edit: (you have had a bug, though, see the other answers)

Categories