【发布时间】: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))。