PHP 在其他函数中使用参数

PHP using Parameters in other functions

关于 OOP 的一般问题我有这个 class

class User{

    //call DB connection
    function User($userId){

    }

    function getMenu(){
        return $userId;
    }
}

我怎样才能通过使用

在 getMenu 函数中访问 $userId
$user = new User($userId);
echo $user->getMenu();

提前致谢。

将其设为 class property:

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 的工作原理