tags:

views:

3221

answers:

8

Is it possible in PHP (as it is in C++) to declare a class method OUTSIDE the class definition?

+1  A: 

No.

You can extend previously declared classes, though, if that helps.

Silver Dragon
+3  A: 

No, as of PHP 5.2. However, you may use __call magic method to forward call to arbitraty function or method.

class A {

    public function __call($method, $args) {
        if ($method == 'foo') {
            return call_user_func_array('bar', $args);
        }
    }

}

function bar($x) {
    echo $x;
}

$a = new A();
$a->foo('12345'); // will result in calling bar('12345')

In incoming PHP 6 there will be (most likely) support for traits. Trait is an implementation of method(s) that cannot be instantiated as standalone object. Instead, trait can be used to extend class with contained implementation. Learn more on Traits here.

Michał Rudnicki
A: 

No it is not posible. if you define function/method outside class construct it becomes global function.

deresh
+2  A: 

You could perhaps override __call or __callStatic to locate a missing method at runtime, but you'd have to make up your own system for locating and calling the code. For example, you could load a "Delegate" class to handle the method call.

Here's an example - if you tried to call $foo->bar(), the class would attempt to create a FooDelegate_bar class, and call bar() on it with the same arguments. If you've got class auto-loading set up, the delegate can live in a separate file until required...

class Foo {

    public function __call($method, $args) {
        $delegate="FooDelegate_".$method;
        if (class_exists($delegate))
        {
             $handler=new $delegate($this);
             return call_user_func_array(array(&$handler, $method), $args);
        }


    }

}
Paul Dixon
A: 

C++ can't do this either. Did you mix up declaration with definition?

Konrad Rudolph
A: 

No, as everyone has said, it is not strictly possible.

However, you can do something like this to emulate a mixin in PHP or add methods to a class at runtime, which is about as close as you're going to get. Basically, it's just using design patterns to achieve the same functionality. Zope 3 does something similar to emulate mixins in Python, another language that doesn't support them directly.

joelhardi
+1  A: 

Yes it is possible to add a method to a PHP class after it is defined. You want to use classkit, which is an "experimental" extension. It appears that this extension isn't enabled by default however, so it depends on if you can compile a custom PHP binary or load PHP DLLs if on windows (for instance Dreamhost does allow custom PHP binaries, and they're pretty easy to setup).

<?php
class A { }
classkit_method_add('A', 'bar', '$message', 'echo $message;', 
    CLASSKIT_ACC_PUBLIC); 
$a = new A();
$a->bar('Hello world!');

Example from the PHP manual:

<?php
class Example {
    function foo() {
        echo "foo!\n";
    }
}

// create an Example object
$e = new Example();

// Add a new public method
classkit_method_add(
    'Example',
    'add',
    '$num1, $num2',
    'return $num1 + $num2;',
    CLASSKIT_ACC_PUBLIC
);

// add 12 + 4
echo $e->add(12, 4);
A: 

If the necesity is to both declare and define the function outside of the class declaration, you indeed have 2 solutions:

a) the __call magic method that can decide a suitable outcome to the request; b) the extension that not all hosts allow;

The first option is the most likely used and it can be used in 2 ways.

a)1) call some global function that lue of the missing method (downside: you will have to write the function in global context, not in class context, so you have to pass "$this" as an argument, and you don't have internal access to private/protected variables). It doesn't matter if the function is in an external file or not.

a)2) include some external file that has the missing methods whole procedure in it so you'll still have full class context (downside: procedure has to be in external file; you need an inclusion mechanism to determine what file to include)

BTW: i found this post trying to see if PHP accepts defining method bodies outside of the class (C++ behavior).

I knew that declaring+defining a new method in a class at runtime could be done as i said above, but was hoping PHP could at least let you declare a function inside the class and define it outside (i was thinking of fragmenting a class declaration into multiple files each file containing a method).

Anyone got a clue what PHP6 will be like regarding this?