Why is my PHP class acting static?
New to PHP.
I have created a simple class:
class User
{
private $name;
private $password;
private $email;
public function getName()
{
return $this->name;
}
public function setName($value)
{
$this->name = $value;
}
public function setPassword($value)
{
$this->password = $value;
}
public function setEmail($value)
{
$this->email = $value;
}
public function getEmail()
{
return $this->email;
}
}
I created 2 instances of this class and stored the first instance into an array. I am then checking to see if the second instance exists in the array (the one 开发者_JS百科I did not add to the array). For some reason in_array() always returns '1' or true.
It turns out that the array now somehow contains the second user object that I did not explicitly add to the array. As if the properties of User are behaving like static class members. What am I missing?
$user = new User();
$user::setName('Nick');
$user::setEmail('bbbb@gmail.com');
$user::setPassword('bbbbb');
$somethingelse = new User();
$somethingelse::setName('Mindy');
$somethingelse::setEmail('a@gmail.com');
$somethingelse::setPassword('aaaa');
$arr = array('users'=>$user); //add first object to array
echo in_array($somethingelse,$arr); //check if second object is in array
echo $arr['users']::getName(); //Prints mindy
}
Because you're using the namespace resolution operator ::
, rather than the instance dereferencing operator ->
. The first invokes the method on the class, the second on an instance. If you turn on E_STRICT
error reporting (which you should!), you'll see a bunch of warnings about calling instance methods statically.
To fix this, use $user->setName('Nick');
(with similar changes elsewhere).
use
->
instead of
::
In short, it’s used to access Static or Constant members of a class.
it would result in
$user = new User();
$user->setName('Nick');
$user->setEmail('bbbb@gmail.com');
$user->setPassword('bbbbb');
$somethingelse = new User();
$somethingelse->setName('Mindy');
$somethingelse->setEmail('a@gmail.com');
$somethingelse->setPassword('aaaa');
$arr = array('users'=>$user); //add first object to array
echo in_array($somethingelse,$arr); //check if second object is in array
echo $arr['users']->getName(); //Prints mindy
精彩评论