[thelist] PHP conditionally create a class method?

sbeam sbeam at onsetcorps.net
Wed Aug 27 12:05:05 CDT 2008


On Wednesday 27 August 2008 02:37, Stephen Rider wrote:
> ARGH!
>
> Sorry -- wrong error message.  The error I'm getting is this:
>
> [27-Aug-2008 01:33:28] hello
> [27-Aug-2008 01:33:28] method doesn't exist
> [27-Aug-2008 01:33:28] PHP Fatal error:  Cannot redeclare myfunction()
> (previously declared in /path/to/my/script.php:17) in /path/to/my/
> script.php on line 17
>
>
> Again... if ( ! method_exists( $this, 'myfunctions' ) ) returns true,
> which should only happen if the method does _not_ already exist.  But
> then I'm getting an error that the method already exists.


'function' is evaluated at compile time. Therefore PHP is "seeing" your 
definition of 'myfunction' regardless of what conditional it is in. 

You can't do 
class test {
	function foo() { function bar() { ... } } 
}
and then call test::bar()
in PHP anyway. bar() is only known within the scope of foo()

Instead, just use inheritance normally and define all your "missing functions" 
in parentclass, redefining as needed in the extensions.

class parentclass {
   function a() { echo 'A '; }
   function b() { echo 'B '; }
   function c() { echo 'C '; }
   function d() { echo 'D '; }
}

class child extends parentclass {
   function a() { echo 'special A from kid! '; }
}

child::a();
child::b();
child::c();
child::d();



More information about the thelist mailing list