-1

我目前正在使用 Zend 1.12 开发一个 Languages 模块(以前从未使用过它)并使用以下代码不断收到标题错误。

<?php if(count($this->getContent('languages')) == 0) : ?>
        <tr><td>No languages were found.</td></tr>
    <?php else : ?>
        <?php foreach($this->getContent('languages') as $language) : ?>
    <tr>
        <td><?php echo $language['language_id']; ?></td>
        <td><?php echo $language['name']; ?></td>
        <td><?php echo $language['iso_shortcode']; ?></td>

getContent() 方法是这样的:

public function getContent($key) {
    if(isset($this->content[$key])) {
        return $this->content[$key];
    } else {
        return false;
    }
}

一位同事以完全相同的方式成功完成了地址模块,所以我想知道这可能是数据库问题吗?我检查了数据库,一切似乎都是对应的。

4

2 回答 2

0

只是为了让您知道如何解决这个问题,或者至少解决这个问题:

<?php if(count($this->getContent('languages')) == 0) : ?>
    <tr><td>No languages were found.</td></tr>
<?php else : ?>
    <?php foreach($this->getContent('languages') as $language) : ?>
<tr>
    <td><?php echo $language['language_id']; ?></td>
    <td><?php echo $language['name']; ?></td>
    <td><?php echo $language['iso_shortcode']; ?></td>

你能做的是删除这条线

if(count($this->getContent('languages')) == 0) 

和替换是

if (!$this->getContent('languages'))

这只是检查返回的值是否为假,如果返回的数组为空,foreach 什么也不做,所以这不会是一个问题。或者:

if (!is_array($this->getContent('languages')))

它检查返回的值是否不是数组。

于 2013-07-26T14:53:25.910 回答
0

Your getContent() method returns false if the specified key does not exist; there are a number of potential problems with this:

1) What if it were valid for an entry in the content member variable to have the value false? Were you actually checking the result, you could not distinguish between absence of the key and a key found with value false. A better choice to indicate absence of an entry would be null, or you could throw an exception.

2) In your use of getContent(), you have assumed that there will be a result for the key 'languages', but have failed to code defensively for the eventuality where there isn't, as has most likely happened here. It would be better either to check that the languages key exists before calling getContent(), to assign the result to a variable and then process it only if it has the expected value (e.g. is not null or is an array in this case), or to throw an exception.

3) A way to mitigate these issues would be with a default parameter to getContent(). The default value would be returned if the expected key does not exist, ensuring that calling code would always work. The default value in this case would be array().

4) As it may be indicative of a bug for a key not to exist, a final nice touch would be either a 3rd parameter to getContent() that specified whether or not the key should exist, or if the default value for the default parameter was e.g. null, to throw an exception if the passed default value was null and the key was not found.

于 2013-07-26T14:29:18.667 回答