Can you code a class function outside of a class in PHP?

In C ++, I code this path:

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

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

I tried to do this in PHP, but the parser will complain. PHP documentation doesn't help either. Can this be done in PHP?

+3
source share
3 answers

Not. You need to include all function definitions inside the class block. If defining your functions in a separate structure makes you feel better, you can use the interface.

interface iBar
{
    function foobar();
}


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

I would suggest just getting used to coding in a new way. It is easily coded sequentially in one language, but I think you are fighting a losing battle if you want to do the same in different languages.

+4
source

You cannot do it in the same way.

interfaces, . , , ( ) .

:

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
    }

}

:

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

class cBarImplementation implements cBar
{
    protected function foobar()
    {
        // do stuff
    }
}
+1

The language does not really provide this function, but if you really want it, you can install the ClassKit extension , which allows you to perform some dynamic class modifications at runtime.

0
source

All Articles