|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2007-06-29 19:12 UTC] mbaynton at gmail dot com
Description:
------------
Just voicing my opinion that it would be nice to be able to create anonymous inner classes as in Java.
Or put another way, I wish something like the reproduce code would work. This looks much better than creating and naming a global class that has some trivial purpose, like the one in the example.
Reproduce code:
---------------
if(! is_object($this->movie))
{
$this->movie = new __Object()
{
public function __call($name, $args)
{
return false;
}
};
}
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Oct 26 04:00:01 2025 UTC |
David, I do not believe you are understanding the request here. I believe this is more what is being requested. class Base { private $name; public function __construct($name) { $this->name = $name; } public function test() { return $this->name; } } $obj = new class extends Base { public function test() { return '<'.$this->name.'>'; } }; echo $obj->test(); Basically similar to that of anonymous functions introduced in PHP 5.3Anonymous classes in Java are convenient when used with Interfaces. In PHP, this could help with MVC frameworks. Say all pages had a class that implemented PageController: [some_page.php] $page_controller = new PageInterface() { function doGet() {} function doPost() {} }; A current workaround would be using a factory or constructor to which you pass required methods, and not using an interface. It works, but then you have to deal with missing methods in application logic where you could otherwise just handle an error.My guess is that anonymous classes would have a good chance once a good implementation comes by. This is not completely trivial as the class_entry has to be stored in the class_table but has to be somewhat hidden and we might have to find a way to hide the information in the oparray. As all things in PHP this needs a volunteer to do it. All contributors have sometime X to work on PHP and in time X can either discuss stuff, fix bugs or implement features ... but with some guidance this might be a nice project for a newcomer (I'd volunteer to give a hand to point in the right direction etc., while this guarantees acceptance in no way as that would need an RFC etc.) until then we have to live with workarounds. For the PageController interface example an (work-around) alternative is $page_controller = [ 'get' => function () {}, 'post' => function () {} };