Defining a public variable based on a session variable

I have a member section for which I use a couple of classes. All of the functions in those classes are dependent on the member_id. When a member log in a session variable member_id is set. I am wondering what would be the most appropriate way to use this session variable in multiple classes. Most people here and elsewere always recommend not to use global variables. So what would be the best way to have access to the member_id within the different classes without making it a global variable?

Thank you in advance

make it a property of the class.

Can you be a bit more precise please

All session data is already in a global state (because of the super global nature of the $_SESSION array), so there’s no need to make the member_id a global. I therefore tend to just access the $_SESSION array directly when I need its data because of its universal availability.

You should probably note, however, that using global data does complicate the unit testing of your classes. This is because you must remember to clean up the state of your global data after each test, otherwise it could have adverse affects on the next test (causing strange failures on seemingly fine tests).

The only other solution to avoiding the use of global data directly is to set an instance variable in your class (either via the constructor or a mutator method) and to reference that variable throughout the class. This avoids the complications in unit testing, though comes with the obvious downside that you must remember to set the instance variable during object creation.

If the object you create is only for working with a single member for the life of the request, then I’d pass the ID in via the constructor. I wouldn’t use a method to set it because if the class needs the member_id to do its job, then passing it in via the constructor makes it clear that its a mandatory dependency - you can’t instantiate the class without it.

class Member {

    protected $pdo;
    protected $memberId;
    
    public function __construct(PDO $pdo, $memberId)
    {
        $this->pdo = $pdo;
        $this->memberId = $memberId;
    }
    
    public function getProfile()
    {
        // Query DB and return profile for $this->memberId;
    }

}

$currentMember = new Member($pdo, $_SESSION['member_id']);

In my opinion, it’s better to pass the ID into the class rather than accessing $_SESSION from within, as the class’s dependency on the member ID is explicit, and the class itself doesn’t need to know where the member_id value comes from - you could retrieve the value from another source without having to modify the class.