PHP在其他函数中使用Parameters

时间:2015-01-12 10:00:33

标签: php oop parameters

关于OOP的一般性问题我有这个课程

class User{

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

    }

    function getMenu(){
        return $userId;
    }
}

如何通过使用

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

提前谢谢。

1 个答案:

答案 0 :(得分:4)

将其设为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的工作原理