PHP检查$ this是否有效

I have an included file in php that can be include from inside a class method or from global scope. $this will be valid in the first case but not the the second.

Is there a way to check if $this is accessible? isset($this) and is_object($this) seem to return true even not being in a method of a class.

Well, when you include the file in a class, then $this is accessible. So you should do a more stringent type check here.

Try using instanceof to determine if $this is what you want:

if ($this instanceof MyObject) {
    // in my class
} else {
    // not in my class
}

http://php.net/manual/en/internals2.opcodes.instanceof.php