PHP在此对象的对象中访问对象函数内的变量

时间:2016-05-27 09:19:44

标签: php function oop object

我有以下问题:

我有一个班级'服务器'的对象。该对象具有变量$ ip和数组$ services []。在数组中是Service类的对象。有没有办法在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变量,那就太好了。

1 个答案:

答案 0 :(得分: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