从另一个类访问对象的属性

Car*_*son 2 php oop

我在PHP中使用OOP,我有以下代码:

index.php文件:

<?php
include('user.class.php');
include('page.class.php');

$user = new User;
$page = new Page;

$page->print_username();
?>
Run Code Online (Sandbox Code Playgroud)

user.class.php:

<?php
class User {

    public function __construct() {

        $this->username = "Anna";
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

page.class.php:

<?php
class Page extends User {

    public function __construct() {
    }

    public function print_username() {

        echo $user->username;
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

我的问题发生在print_username()函数中的"Page"类中.

如何在此类中访问$ user对象的属性?正如您所看到的,我在index.php中定义了两个对象.

提前致谢

/C

Cod*_*gry 7

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();
Run Code Online (Sandbox Code Playgroud)

$user应该是$this.