Accessing object's properties from another class
oop, php
Solution
class User {
public $username = null;
public function __construct() {
$this->username = "Anna";
}
}
class Page extends User {
public function __construct() {
// if you define a function present in the parent also (even __construct())
// forward call to the parent (unless you have a VALID reason not to)
parent::__construct();
}
public function print_username() {
// use $this to access self and parent properties
// only parent's public and protected ones are accessible
echo $this->username;
}
}
$page = new Page;
$page->print_username();
`$user` should be `$this`.
Problem
I'm playing around with OOP in PHP and I've got the following code: index.php: ``` <?php include('user.class.php'); include('page.class.php'); $user = new User; $page = new Page; $page->print_username(); ?> ``` user.class.php: ``` <?php class User { public function __construct() { $this->username = "Anna"; } } ?> ``` page.class.php: ``` <?php class Page extends User { public function __construct() { } public function print_username() { echo $user->username; } } ?> ``` My problem occurs in the class "Page", in the print_username() function. How do I access the $user object's properties within this class? I am, as you can see, defining the two objects in index.php. Thanks in advance /C