Php 具有(n个深度)对象getter的Isset
使用条令的Zend框架项目。 数据以对象的形式出现。在我的Zend视图中,我访问它就像Php 具有(n个深度)对象getter的Isset,php,zend-framework,doctrine-orm,Php,Zend Framework,Doctrine Orm,使用条令的Zend框架项目。 数据以对象的形式出现。在我的Zend视图中,我访问它就像 $this->personData->getPersonAdress()->getPersonStreet(); 由于一个人可能没有关联的地址,我们必须在回音之前检查PersonalAddress是否存在,personStreet是否已填充,否则可能会发生回音空错误 因此,我们在isset中使用了一些IFs: <? if($this->personData->getPer
$this->personData->getPersonAdress()->getPersonStreet();
由于一个人可能没有关联的地址,我们必须在回音之前检查PersonalAddress是否存在,personStreet是否已填充,否则可能会发生回音空错误
因此,我们在isset中使用了一些IFs:
<? if($this->personData->getPersonaddress()) echo $this->personData->getPersonaddress()->getPersonstreet(); else echo "''"?>
您可以告诉条令使用数组返回数组,而不是映射对象
这样,就可以直接调用isset()。可以在链的前面加上@,这会抑制错误输出,这样就根本不需要检查它了。如果它不存在,它就不会输出任何东西
<?php echo @$this->personData->getPersonAdress()->getPersonStreet(); ?>
通常不建议使用@operator,但在这种情况下,它似乎是一个合适的解决方案。(缺点是您可能会错过这一行中可能出现的其他错误)我自己解决了这个问题,实现了一个Zend View帮助程序,它可以打印出每个值,忽略非对象属性或空关联可能出现的错误。
这对所有使用Zend Framework+Doctrine 2的人都很有用
用法
而不是
$this->address[0]->getAddress()->getCountry()->getCountryId()
使用(如果未设置,则提供值或默认值(0,第三个参数)
$this->Printsafe($this->address[0],“getAddress/getCountry/getCountryId”,0)
代码跟踪
这是可行的,但需要在视图中进行大量重构。没有选择,但是谢谢。
<?php echo @$this->personData->getPersonAdress()->getPersonStreet(); ?>
class Printsafe extends Zend_View_Helper_Abstract {
public function isObjectOrSet($data, $properties)
{
if ($data != null)
{
if(is_object($data))
{
if (isset($properties[0]))
{
$actual_property = array_shift($properties);
return $this->isObjectOrSet($data->{$actual_property}(), $properties);
}
}
elseif(isset($data))
{
return $data;
}
else
return null;
}
else
return null;
}
/**
* Wants data and getters + properties
* Tests if they are set and returns requested value
* Returns empty value (instead of NULL) if any error occurs
*
* @param mixed $data - Example $this->personData
* @param string $properties - Example "getPersontype/getNotation"
* @param mixed $default - return value if not set. Default is empty string.
*
* @return mixed $value
*/
public function printsafe($data = null, $properties='', $default = '') {
$return = null;
if ($data != null)
{
if ($properties != '')
{
$prop_array = explode("/", $properties);
$return = $this->isObjectOrSet($data, $prop_array);
}
}
if ($return == null)
$return = $default;
return $return;
}
}