I have a page class for my web page. When this is called, it creates a new user. This allows me to check if there is a user logged in. Here is the construct method from the page class:
public function __construct() {
// check user is logged in
require 'classes/user.class.php';
$user = new user();
if(!$user->isLoggedIn()) {
// user is not logged in
// load login page
}
else {
// user is logged in
// load requested page
}
}
The whole user validation thing is working just fine, but I now want to access the user object that was created during page construction. Is this a possibility with the way I’m going about things, and if so, how do I access the user object?
To be honest, this a a pretty moot design. Better would be creating the user object outside of the page context then “injecting” it where needed:
Basically, avoid initiating classes from inside of object methods. This lead to non maintainable and non testable code. Especially when you’ll need to “mock” the instances with mock services. I’d recommend you rethink the design, the one you have will only get smellier with time.