【问题标题】:PHP Access a variable inside a function of an object in an object of this objectPHP 在这个对象的一个​​对象中访问一个对象的函数内部的一个变量
【发布时间】:2016-05-27 09:19:44
【问题描述】:

我有以下问题:

我有一个“服务器”类的对象。该对象具有变量 $ip 和数组 $services[]。数组中是服务类的一个对象。有没有办法在 Service 对象的函数中访问变量 $ip?

class Server
{
    private ip;
    private services = [new Service()];
}

class Service
{
    function checkServiceStatus()
    {
        connectToServer($IP);
        // I need the IP of the Server it belongs to, in order to
        // connect to the server and check its status
    }
}

$WindowsServer = new Server();

这是我的问题的简单代码示例。如果我可以访问 Service 对象所属的 Server 对象的 $IP 变量,那就太好了。

【问题讨论】:

  • 这取决于您将如何使用$ip 的值(这就是为什么您的问题的代码示例很有用)。如果要从Server 的另一个方法中调用数组中保存的Service 实例的方法,则可以将$this->ip 作为参数传递给该方法调用。如果您将$ip 的值保留为Service 实例的属性,则在存储到数组之前将其作为参数传递给构造函数(例如$services[] = new Service($this->ip))。

标签: php function oop object


【解决方案1】:

只需将@jeyoung 注释转换为代码:

class Server
{
    private $ip;
    private $services = [];

    function __construct($ip) {
      $this->ip = $ip;
      $this->services[] = new Service($this->ip);
    }
}

class Service
{
    function __construct($ip) {
      $this->ip = $ip;
    }

    function checkServiceStatus()
    {
        connectToServer($this->ip);
        // I need the IP of the Server it belongs to, in order to
        // connect to the server and check its status
    }
}

$WindowsServer = new Server('127.0.0.1'); // for example

【讨论】:

  • 您缺少Server 中的构造函数,并且您没有将$ip 提供给new Service()
  • 谢谢,我写得太快了... :-(
  • 感谢您的回答:),我也想到了这个解决方案,但我认为可能有一种方法可以每次直接从服务器对象读取它。这样如果服务器 ip 发生变化,服务也会使用正确的 ip。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 2016-06-08
  • 2013-05-02
相关资源
最近更新 更多