我有以下问题:
我有一个班级'服务器'的对象。该对象具有变量$ 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变量,那就太好了。
答案 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