|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2004-07-12 09:41 UTC] tomas_matousek at hotmail dot com
Description:
------------
Declaration of a function in a method doesn't work.
IMHO by declaring a function in a method one creates a function not a method. It it was a method it would be possible to call it by $a->f(). That works neither.
See the code below:
Reproduce code:
---------------
class A
{
function g()
{
echo "function g - begin\n";
function f()
{
echo "function f\n";
}
echo "function g - end\n";
}
}
$a = new A;
$a->g();
f();
Expected result:
----------------
function g - begin
function g - end
function f
Actual result:
--------------
function g - begin
function g - end
Fatal error: Non-static method A::f() cannot be called statically ...
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Sun Nov 02 17:00:02 2025 UTC |
While nested functions are maybe useful feature for someone declaration of a function inside the body of a method (which happens to be a function inside a class) is _ambigious_ . Why? There is no reserved word "method" for marking methods of a class and "function" is used so when it is between {} after class name "function" creates a method of the class. IMO "function" inside a method should not be possible.IMHO, Nested Functions are BAD&WRONG, thus they should be disabled. Firstly, when you DECLARE a function inside a function, you have a redeclaration problem. Try to execute the parent function twice and most likely you'll receive a message: "Fatal error: Cannot redeclare XXXX". OK! Some may dispute: "let's create an undeclare_function() so as to allow at the end of the function undeclare the child function. It would enable to reinvoke the parent function whenever we like". Well, THIS IS ALSO B&R. Why would you undeclare a function that you're going to use? Secondly, if a function needs to work in a closed (encapsuled) environment, well, I think you need a CLASS, not a function. In a class you may have a public, private or protected variables invoked by either public, private or protected methods. Thusly, a code like this (sorry the indentation, I want to save space): class A { function b(){} function c(){} function d(){} function g(){ echo "function g - begin\n"; function f(){echo "function f\n";} echo "function g - end\n"; } } should be written like this: class A { function b(){} function c(){} function d(){} function g(){ echo "function g - begin\n"; f::f(); echo "function g - end\n"; } } class f{ function f(){echo "function f\n";} } $obj = new A(); $obj->g(); So, the rationale is, why you need to have function within function if you've got classes?