Anonymous functions as properties in Classes in PHP

By: Schaffhirt A Viewed: 153178 times    

When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.


Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.


Consider the following example:


<?php
class MyClass {
        const member = 1;
        public $member;
        public function member () {
            return "method 'member'";
        }
        public function __construct () {
$this->member = function () {
                return "anonymous function 'member'";
            };
        }
    }
header("Content-Type: text/plain");
$myObj = new MyClass();
var_dump(MyClass::member);  // int(1)
var_dump($myObj->member);   // object(Closure)#2 (0) {}
var_dump($myObj->member()); // string(15) "method 'member'"
$myMember = $myObj->member;
var_dump($myMember());      // string(27) "anonymous function 'member'"
?>


That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial