我在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
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.
| 归档时间: |
|
| 查看次数: |
3377 次 |
| 最近记录: |