Programming Tutorials

Anonymous functions as properties in Classes in PHP

By: Schaffhirt A in PHP Tutorials on 2011-10-29  

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:

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.

Add Comment

* Required information


No comments yet. Be the first!

Most Viewed Articles (in PHP )

Perl's Encoding::FixLatin equivalent in PHP

How to fix: Warning: Visiting this site may harm your computer -

Traversing Arrays Using list() and each() in PHP

GDBM, NDBM, DB2, DB3, DBM, and CDB Databases in PHP

A Tutorial on Timezones and Timestamps

Decrypting files using GnuPG (GPG) via PHP

error: "Service Unavailable" after installing PHP to a Windows XP x64 Pro

Return multiple values from a function in PHP

isset() function in PHP

PHP ./configure RESULTING IN __rcp_thread_des[email protected]_2_2_3_... AND UNRESOLVED REFERENCES WITH ORACLE OCI8

Anonymous functions as properties in Classes in PHP

Cannot load /usr/local/apache/libexec/ into server:

Installing PHP with nginx-server under windows

Setting up PHP in Windows 2003 Server IIS7, and WinXP 64

Running different websites on different versions of PHP in Windows 2003 & IIS6 platform

Latest Articles (in PHP)