tags:

views:

344

answers:

5

Hello there

I am wondering if php methods are ever defined outside of the class body as they are often done in C++. I realise this question is the same as http://stackoverflow.com/questions/71478/defining-class-methods-in-php . But I believe his original question had 'declare' instead of 'define' so all the answers seem a bit inappropriate.

Thanks

Zenna

Update

Probably my idea of define and declare were flawed. But by define outside of the class body, i meant something equivalent to the C++

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
};

void CRectangle::set_values (int a, int b) {
  x = a;
  y = b;
}

All the examples of php code have the the code inside the class body like a C++ inlined function. Even if there would be no functional difference between the two in PHP, its just a question of style.

A: 

No. You can consider 'declare' and 'define' to be interchangeable in that question.

chaos
+1  A: 

It's possible, but very, very hacky and not recommended. No reason to do it either.

Jani Hartikainen
+1  A: 

First of all, in PHP, all class methods must be defined and implemented within the class structure (class x { }). It is in no way like C++ where you have the implementations (*.cpp) separate from the definitions (*.h).

sirlancelot
A: 

Having the declaration of methods in header files separate from their implementation is, to my knowledge, pretty unique to C/C++. All other languages I know don't have it at all, or only in limited form (such as interfaces in Java and C#)

Michael Borgwardt
+1  A: 

Here is a terrible, ugly, hack that should never be used. But, you asked for it!

class Bar {
    function __call($name, $args) {
        call_user_func_array(sprintf('%s_%s', get_class($this), $name), array_merge(array($this), $args));
    }
}

function Bar_foo($this) {
    echo sprintf("Simulating %s::foo\n", get_class($this));
}

$bar = new Bar();
$bar->foo();

What have I done? Anyway, to add new methods, just prefix them with the name of the class and an underscore. The first argument to the function is a reference to $this.

Justin Poliey