-6ren">
gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 08:44:02 25 4
gpt4 key购买 nike

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

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;
}
}
?>

我的问题出现在“Page”类的 print_username() 函数中。

如何在此类中访问 $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();

$user 应该是 $this

关于php - 从另一个类访问对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17662004/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com