0

I don't quite understand why the array I declared as a public class member is accessible from within the class' constructor but not from any other method within the class. The program I'm making involves storing Album objects (generated black squares) within an album container object. It's also important that I mention I'm doing this locally using XAMPP.

Here is the albumContainer class:

<?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/>";
        }
    }
}

?>

Here is the album class:

<?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;
    }
}

?>

Lastly, here is the main page where I instantiate the album contained the object and call the render method:

<?php
    //autoloader
    function autoloadFunction($class)
    {
        require('classes/' . $class . '.php');
    }
    //set up autoloader
    spl_autoload_register('autoloadFunction');

    $collage = new albumContainer;
    $collage::render();
?>

Every time I run the code I get the following message:

Fatal error: Uncaught Error: Using $this when not in object context in C:\xampp\htdocs\Web Development\char­ts4all.com\sub­pages\classes\al­bumContainer.php:26 Stack trace: #0 C:\xampp\htdocs\Web Development\char­ts4all.com\sub­pages\home.php(11): albumContainer::ren­der() #1 C:\xampp\htdocs\Web Development\char­ts4all.com\in­dex.php(42): include('C:\xam­pp\htdocs...') #2 {main} thrown in C:\xampp\htdocs\Web Development\char­ts4all.com\sub­pages\classes\al­bumContainer.php on line 26

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
  • 3
    Change `$collage::render();` to `$collage->render();` and it will work. Using `::` instead of `->` calls the method statically. You need to call it on the instance or `$this` won't exist in the methods scope. – M. Eriksson Mar 29 '18 at 05:47
  • 1
    Possible duplicate of [What's the difference between :: (double colon) and -> (arrow) in PHP?](https://stackoverflow.com/questions/3173501/whats-the-difference-between-double-colon-and-arrow-in-php) – M. Eriksson Mar 29 '18 at 05:51

1 Answers1

4

You are calling render function as a static method on object which is wrong.

 $collage::render(); //Wrong way
 $collage->render();
Pramod Patil
  • 2,704
  • 2
  • 14
  • 20