Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods defined outside class?

Tags:

c++

oop

php

class

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 Defining class methods in PHP . But I believe his original question had 'declare' instead of 'define' so all the answers seem a bit inappropriate.

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.

like image 893
zenna Avatar asked Aug 14 '09 20:08

zenna


3 Answers

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.

like image 122
Justin Poliey Avatar answered Nov 03 '22 02:11

Justin Poliey


I stumbled upon this question while looking for a way to separate declaration and implementation of class methods. Why? For the sake of code readability. When the declarations are in a separate file, or at the top of the class file, someone looking to use the class does not have to wade through the whole implementation to find out which methods are offered.

I did find something useful though: PHP interface classes. I don't think they are designed for it, but they serve the purpose: an interface class defines all the methods, and then the "real" class implements them. Here's an article about it:

http://www.davegardner.me.uk/blog/2010/11/21/why-you-should-always-use-php-interfaces/

like image 5
littlegreen Avatar answered Nov 03 '22 02:11

littlegreen


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#)

like image 4
Michael Borgwardt Avatar answered Nov 03 '22 01:11

Michael Borgwardt