Reputation: 137
So yeah, I was wondering if you can do it..
class Ping
{
function __construct()
{
return self::ping();
}
private static function ping()
{
if ((1 - 1) == 0)
{
return false;
}
else
{
return true;
}
}
}
And usage is:
Class ServerHandler
{
public function check()
{
if (new Ping())
{
ECHO 1;
}
else
{
echo 2;
}
}
}
So basically, it doesn't work. My website is echoing '1' instead of '2' cause false
must return
'2'.
Basically, I want to check if it returns true
or false
.
For example, a boolean variable can do that:
if (variable)
{
then...
}
But why can't a class do that? I mean I am returning the boolean, using the constructor? Why doesn't it work?
Upvotes: 1
Views: 1682
Reputation: 212402
Because the constructor is used to instantiate the class, and what you get returned
is the instance itself.... though look at the new features in PHP 5.5
EDIT
I'd thought I'd read something about dereferencing (similar to array dereferencing) from an object constructor being implemented in PHP 5.5, but can't find any references to it at the moment
Upvotes: 5
Reputation: 2587
If you do not call construct function directly, it will always return an object.
BUT, you can do:
$ob = new Ping();
$ob->__construct();
Second line of code will return what's written in your constructor function's return
. In your case it should return false
.
Upvotes: 1
Reputation: 17161
I don't think PHP cares about your return statement in your constructor. It should always return the object that was created (the instance of Ping). Since the instance of Ping is not null, if(new Ping())
evaluates to true
and '1' is echoed.
If pinging is really just one call, why use an object? You can have this statically defined in a static library of some sort (e.g. NetUtils). If pinging is more complex and you think that it fits the object oriented model, then perform the ping in two steps.
Ping pingObj = new Ping();
pingObj->ping();
Upvotes: 3