0

I'm fairly new to object orientated programming, so bear with me if I've missed something simple, or done something wrong.

I have a set up where the domains class can contain details on a domain name (such as name, expiry, creation date etc.), but can also have a $hosting variable which relates to the hosting account that the domain is tied with. However, not all domains are hosted and are just there waiting to be used, so the hosting object doesn't always exist.

In both domains and hosting I have functions to return the relevant details, so for example:

private $accountId;
private $name;
private $created;

public function getAccountId() {    return $this->accountId;        }
public function getName() {     return $this->name;     }
public function getCreated() {  return $this->created;  }

So, if I wanted the hosting accounts id from within the domain object (called $domain) I could do:

$domain->getHosting()->getId();

Hopfully that makes sense!

If there is a hosting account, the ID is returned: PHP Fatal error: Call to a member function getAccountId() on a non-object in /home/sites/.../file.php on line x

Is there a way of checking if $domain->getHosting() exists to prevent this error?

Many Thanks in advance, and sorry if this is a simple error!

4

6 回答 6

3

实际上,您没有一种类型,而是两种:

class Domain {
   ....
}

class HostedDomain extends Domain {
   ...
}

相应地编写您的代码。HostedDomain比 更具体一点Domain。它可以在任何Domain适合的地方以及一些额外的特殊地方使用。

然后,您可以检查每个域是否托管;

if ($domain instanceof HostedDomain) {
    ...
}

请参阅对象继承类型运算符

于 2012-10-13T01:21:40.403 回答
1

您可以使用 PHP method_exists

   if(method_exists($domain,'getHosting')){ ... }
于 2012-10-13T01:16:00.020 回答
1

或者,如果您真的想检查该类是否存在:

if (class_exists('Domain')) { ... }
于 2012-10-13T01:19:59.020 回答
1

我的 PHP 有点生疏,但我相信isset($hosting)在域对象中会有所帮助,或者作为域类中的方法(例如 hasHost)来检查主机是否存在,或者只是isset($domain->getHosting()). 假设您在没有主机的情况下从未设置 $hosting,那么 isset 应该做您想做的事情。

于 2012-10-13T01:22:39.920 回答
0

只需在使用前检查 getHosting 是否存在

if (! $domain->getHosting()) {
   $value = $domain->getHosting()->getId();
}
于 2012-10-13T01:17:19.457 回答
0

由于您的方法getHosting()返回一个对象,您应该将值存储到一个临时变量中,检查该变量是否为空,如果它不为空,您可以使用它:

$hosting = $domain->getHosting();
if (!empty($hosting)) {
    $id = $hosting->getId();
}

您有几个选择,除了empty(). 您还可以使用isset(),is_object()或检查 if $hosting != null- all 应该为您提供在这种情况下所需的相同逻辑。

当然,这一切都假设该getHosting()方法存在于Domain类中(其他一些答案所解决的问题)。

于 2012-10-13T01:20:37.170 回答