如何在php中创建对象(如c#)
对于具有3个属性的示例用户</ p>
class Users
{
private $name;
private $age;
private $sex;
public function __construct($name, $age, $sex) {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
}
如何在集合中添加用户 然后循环用户集合以获取
$user->name
$user->age
$user->sex
谢谢
答案 0 :(得分:0)
从你给出的例子来看,它可能是这样实现的:
class User
{
const
SEX_M = 1,
SEX_F = 2
;
private
$name,
$age,
$sex
;
public function __construct($name, $age, $sex) {
$this->name = $name;
$this->age = $age;
$this->sex = $sex;
}
public function dump()
{
echo "name: $this->name, age: $this->age, sex: "
. ($this->sex === User::SEX_M ? 'm' : 'f') . "<br>\n";
}
}
$collection = array();
$collection[] = new User('Tom' , 10, User::SEX_M);
$collection[] = new User('Jerry', 11, User::SEX_F);
foreach ($collection as $user)
$user->dump();