PHP Checking variables isset, empty, defined etc
i was looking at a tutorial from ZendCasts where i wondered about the code he used. a simplified version below
class TestClass {
private $_var;
private static function getDefaultView() {
if (self::$_var === null) { ... } // this is the line in question
}
}
i wonder why is something开发者_如何学JAVA like isset(self::$_var)
not used instead?
when i use self::
i need the $
sign to refer to variables? i cant do self::_var
?
how does ==
differ from ===
These are several questions.
I wonder why is something like isset(self::$_var) not used instead
It's indifferent. The advantage of using isset
is that a notice is not emitted if the variable ins't defined. In that case, self::$_var
is always defined because it's a declared (non-dynamic) property. isset
also returns false if the variable is null
.
when i use self:: i need the $ sign to refer to variables?
Note that this is not a regular variable, it's a class property (hence the self
, which refers to the class of the method). Yes, except if this is a constant. E.g.:
class TestClass {
const VAR;
private static function foo() {
echo self::VAR;
}
}
how does == differ from ===
This has been asked multiple times in this site alone.
- For the == and === operators, see the manual page.
- For the self, see here
The ===
operator means "equal and of same type", so no automatic type casting happens. Like 0 == "0"
is true, however 0 === "0"
is not.
The self::$var
syntax is just the syntax. use $ to refer to a variable, no $ to refer to a function.
The self::
syntax is used for static access (class variables, class methods, vs. instance variables refereed to by this
).
精彩评论