tags:

views:

252

answers:

4

In C++, I code this way:

//foo.h    
class cBar
{
    void foobar();
}


//foo.cpp
void cBar::foobar()
{
    //Code
}

I tried to do this on PHP but the parser would complain. PHP's documentation also doesn't help. Can this be done in PHP?

+2  A: 

Simple answer: no, you can't.

Konrad Rudolph
A: 

You can't really do this in the same manner.

You can use class abstraction and interfaces, though. The main difference between the two is that and interface does not allow you to specify the function body, where (not abstract) methods in an abstract object can hold all kinds of default behaviour.

Abstraction:

abstract class cBar
{
    // MUST be extended
    abstract protected function foobar();

    // MAY be extended
    protected function someMethod()
    {
        // do stuff
    }
}

class cBarExtender extends cBar
{
    protected function foobar()
    {
        // do stuff
    }

}

Interfacing:

interface cBar 
{
    // MUST be implemented
    protected function foobar();
}

class cBarImplementation implements cBar
{
    protected function foobar()
    {
        // do stuff
    }
}
Aron Rotteveel
+3  A: 

No. You need to including all your function definitions inside the class block. If defining your functions in a separate structure makes you feel better you could use an interface.

interface iBar
{
    function foobar();
}


class cBar implements iBar
{
    function foobar()
    {
        //Code
    }
}

I'd suggest just getting used to coding in a new way. It's easy to code consistantly within a single language, but I think you are fighting a loosing battle if you want to do the same across languages.

Josh
Everyone gave great answers. But I've chosen your answer because of this quote: It's easy to code consistantly within a single language, but I think you are fighting a loosing battle if you want to do the same across languages.
MrValdez
A: 

The language doesn't really provide this feature but if you really want it, you can install the ClassKit extension which will let you do some dynamic class modifications at run-time.

Sean McSomething