-1

我环顾四周寻求帮助。我意识到这可能更多地与我使用对象的方式有关(我是 OO PHP 的新手),但这真的让我很烦恼。这是我正在尝试做的一个大大简化的版本:

<?php
class Show_message {
    public $message_instance = ""; //ensure Message object variable is visible
    function __construct() {
    //do nothing
    }
    function display_message() {
        $message_instance = new Message(); //instatiate Message object
        echo $message_instance->message . " : in display_message function <br>"; //works
    }
    function display_again() {
        echo $message_instance->message . " : in display_again function <br>"; //does not work
    }
}
class Message {
    public $message = ""; //ensure $this->message variable is visible?
    function __construct() {
        $this->message = "Hello world"; //make message
    }
}
$instance = new Show_message(); //instatiate Show_message object
$instance->display_message(); //method to create instance and display message
$instance->display_again(); //method to display message again
?>

为什么函数$message_instance->message不可见display_again()

4

2 回答 2

3

您需要使用$this->,否则您将Message对象本地存储到函数,而不是类实例。

$this->message_instance = new Message();

以及$this->message_instance你在做什么$message_instance

于 2013-05-26T15:12:53.507 回答
0

工作演示

因为您local在函数内部设置了一个变量,所以您必须使用它$this来访问对象属性。

<?php
class Show_message {
    public $message_instance = ""; //ensure Message object variable is visible
    function __construct() {
        $this->message_instance = new Message();
    }
    function display_message() {
         //instatiate Message object
        echo $this->message_instance->message . " : in display_message function <br>";
    }
    function display_again() {
        echo $this->message_instance->message . " : in display_again function <br>";
    }
}
class Message {
    public $message = ""; //ensure $this->message variable is visible?
    function __construct() {
        $this->message = "Hello world"; //make message
    }
}
$instance = new Show_message(); //instatiate Show_message object
$instance->display_message(); //method to create instance and display message
$instance->display_again(); //method to display message again
?>
于 2013-05-26T15:19:51.810 回答