user1187347
user1187347

Reputation: 328

Accessing a class created within another class

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?

Upvotes: 1

Views: 92

Answers (4)

smassey
smassey

Reputation: 5931

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:

# page.php
class Page {
    # private $_user; # maybe ... probably not needed.
    public function __construct( User $user ) {
        if ( $user->isLoggedIn() ) { /* etc */ }
        # if this will be needed in other functions, save a copy of the
        # obj reference to as an object attribute:
        $this->_user = $user;
    }
}

# user.php
class User {
    public function isLoggedIn() { /* etc */ }
}

# request_controller.php
$user = new User();
$page = new Page( $user );

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.

Upvotes: 4

Rem.co
Rem.co

Reputation: 3821

<?php
require_once 'classes/user.class.php';
class page {
    private $myUser;

    public function __construct() {
        // check user is logged in

        $this->myUser = new user();
        if(!$this->myUser->isLoggedIn()) {
            // user is not logged in
            // load login page
        }
        else {
            // user is logged in
            // load requested page
        }       
    }

    public function getUser() {
        return $this->myUser;
    }
}

$p = new page();

$user = $p->getUser();
?>

Should do the trick for you.

Upvotes: 1

David
David

Reputation: 4117

You can store the object in the session and then access it anywhere.

Upvotes: 0

sebataz
sebataz

Reputation: 1043

I can put user as an instance variable and then access it with the keyword $this->

example:

class Page {
    public $user; // private if you want to access it only within Page

    public function __contruct() {
        $this->user = new user();
        // rest of your code
    }
}

Upvotes: 1

Related Questions