[英]Variable trouble in 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>";
}
?>
您的$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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.