关于OOP的一般问题 我有这个类
class User{
//call DB connection
function User($userId){
}
function getMenu(){
return $userId;
}
}
我如何能够仅使用 getMenu 函数中的$userId
$user = new User($userId);
echo $user->getMenu();
提前谢谢你。
通过使其成为类属性:
class User{
//Since you're not inheriting you can also make this property private
protected $userId; //Or private $userId;
/* As of PHP 5.3.3, methods with the same name as the last element of a
namespaced class name will no longer be treated as constructor.
This change doesn't affect non-namespaced classes.*/
//call DB connection
public function __construct($userId){
$this->userId = $userId;
}
public function getMenu(){
return $this->userId;
}
}
这确实是OOP的基础,我建议您阅读一些教程来解释OOP的工作原理