PHP强制接口实现

I have an SystemInfoFactory class in my application which has a getSystemInfo() method:

/**
 * Returns SystemInfo object based on which OS
 * server uses
 *
 * @return SystemInfoInterface SystemInfo object
 */
public function getSystemInfo()
{
    $os = $this->getOS();

    $systemInfo = null;

    switch ($os) {
        case "Linux":
            $systemInfo = new LinuxInfo();
            break;
        case "Darwin":
            $systemInfo = new OSXInfo();
            break;
        case "Windows":
            $systemInfo = new WindowsInfo();
            break;
    }
    return $systemInfo;
}

So it chooses appropriate object according to host system. Now, each "info class" implements SystemInfo interface (methods like getArchitecture, getCPU etc.), but as you see, nowhere in my code is it checked whether returned object really implements interface. Would it be considered "good practice" to check if selected $systemInfo object implements it before returning it? It obviously isn't required, but in case somebody extends this application (adds BSD support for example) and forgets to implement all methods it might be harder for him to debug.

Absolutely it would be good practice. You are defining in your docblock that your method returns an instance of SystemInfo. Your callers should be able to rely on that. This is simple in your code:

/**
 * Returns SystemInfo object based on which OS
 * server uses
 *
 * @return SystemInfoInterface SystemInfo object
 */
public function getSystemInfo()
{
    $os = $this->getOS();

    $systemInfo = null;

    switch ($os) {
        case "Linux":
            $systemInfo = new LinuxInfo();
            break;
        case "Darwin":
            $systemInfo = new OSXInfo();
            break;
        case "Windows":
            $systemInfo = new WindowsInfo();
            break;
        default:
            throw new \RuntimeException('System not supported');
            break;
    }

    if (!$systeminfo instanceof SystemInfo) {
        throw new \RuntimeException('Invalid SystemInfo object returned');
    }

    return $systemInfo;
}

Make sure you declare that you'll be throwing exceptions from this method call. The exception here makes it very clear what's going on, rather than having to chase through an "undefined method" error later on in the code.

I think, the keyword in here is Duck Typing. The interface of an object is defined by its methods and attributes rather than its ancestors and implemented interfaces.

Have a look at this: http://en.wikipedia.org/wiki/Duck_typing

Back to PHP: It's perfectly valid and no bad style if you do not check if the object implements your interface. If the code crashes the implementor of the class has to be blamed. I would find it annoying if the code is messed up with if ($obj instanceof FancyInterface) {.