我不太明白为什么我声明为公共类成员的数组可以从类的构造函数中访问,但不能从类中的任何其他方法访问。我正在制作的程序涉及在相册容器对象中存储相册对象(生成的黑色方块)。同样重要的是,我提到我在本地使用XAMPP进行此操作。
这是albumContainer类:
<?php
require("album.php");
class albumContainer
{
public $Albums = [];
public function __construct()
{
for($i = 0; $i < 3; $i++)
{
for($j = 0; $j < 3; $j++)
{
$this->Albums[] = new Album;
}
}
}
public function render()
{
for($i = 0; $i < 3; $i++)
{
for($j = 0; $j < 3; $j++)
{
echo $this->Albums[$i + $j]->pass()." ";
}
echo "<br/>";
}
}
}
?>
这是专辑类:
<?php
class Album
{
var $source;
function __construct(){
$img = imagecreate(200,200);
$bgcol = imagecolorallocate($img, 0,0,0);
imageline($img, 0, 0, 200, 200,$bgcol);
imagepng($img, "album.png");
$this->source = "<img src = 'album.png'/>";
}
function pass(){
return $this->source;
}
}
?>
最后,这是我实例化包含对象的相册并调用render方法的主页面:
<?php
//autoloader
function autoloadFunction($class)
{
require('classes/' . $class . '.php');
}
//set up autoloader
spl_autoload_register('autoloadFunction');
$collage = new albumContainer;
$collage::render();
?>
每次运行代码时,都会收到以下消息:
致命错误:未捕获错误:在C:\ xampp \ htdocs \ Web Development \ charts4all.com \ subpages \ classes \ albumContainer.php中不在对象上下文中时使用$ this:26堆栈跟踪:#0 C:\ xampp \ htdocs \ Web Development \ charts4all.com \ subpages \ home.php(11):albumContainer :: render()#1 C:\ xampp \ htdocs \ Web Development \ charts4all.com \ index.php(42):include( 'C:\ xampp \ htdocs ...')在第26行的C:\ xampp \ htdocs \ Web Development \ charts4all.com \ subpages \ classes \ albumContainer.php中抛出#2 {main}
答案 0 :(得分:4)
您正在调用渲染函数作为对象的静态方法,这是错误的。
$collage::render(); //Wrong way
$collage->render();