在php中可变的麻烦

时间:2013-12-24 02:19:41

标签: php

我正在尝试制作一个自动化功能,在我的网站上制作“卡片”,并且出于某种原因它说我没有在第18行定义一个数组,即使它是在3上定义的。

这是错误:

Notice: Undefined variable: cardArray in 
E:\XAMPP\htdocs\Websites\website\pages\featured.php on line 18

Notice: Undefined variable: cardArray in 
E:\XAMPP\htdocs\Websites\website\pages\featured.php on line 18

以下是代码:

<?php

$cardArray = array();   

newCard("Eltit", "This is some interesting text that everyone wants to read because it is awesome. The said this is, is that people might not be able to comprehend it.", "James.png");
newCard("Eltit 2!", "This is just some more interesting works to feast your eyes on mainly because this website doesn't have any content to fill it up yet :)");

for ($i=1; $i < count($cardArray); $i++) { 
    makeCard($cardArray[i][0], $cardArray[i][1], $cardArray[i][2]);
}

//<<--    Functions    -->>//

function newCard($title = "Title", $text = "Text", $avatar = "DefaultUserIcon.png") {

    $tempArray = array($title, $text, $avatar);

    $cardArray[count($cardArray)+1] = $tempArray;

}

function makeCard($title, $text, $avatar) {

    echo "
        <div class='box'>
            <div id='profile' style='background: url('../img/avatars/".$avatar."');'>
                <div id='avatar'></div>
                <div id='info'>
                    This is where the user info will go.
                </div>
            </div>
            <div id='content'>
                <div id='description'> 
                    <h1>".$title."</h1>
                    ".$text."
                </div>
            </div>
            <div id='footer'>
                <div style='padding: 18px;'>
                    This is where the buttons will be.
                </div>
            </div>
        </div>";

}
?>

1 个答案:

答案 0 :(得分:2)

您的$cardArray变量位于全局范围内。要在函数中使用,您需要在函数内声明它为global

function newCard($title = "Title", $text = "Text", $avatar = "DefaultUserIcon.png") {
    global $cardArray;

    $tempArray = array($title, $text, $avatar);
    $cardArray[count($cardArray)+1] = $tempArray;
}

虽然这可以解决您的问题。建议不要使用global,建议将它们作为参数传递给函数。

示例:

function newCard($title = "Title", $text = "Text", $avatar = "DefaultUserIcon.png", $cardArray) {
    $tempArray = array($title, $text, $avatar);
    $cardArray[count($cardArray)+1] = $tempArray;
}

然后所有来电者都会将$cardArray传递给newCard函数:

newCard("Eltit", "This is some interesting text that everyone wants to read because it is awesome. The said this is, is that people might not be able to comprehend it.", "James.png", $cardArray);