Marco Maserati
Marco Maserati

Reputation: 40

How to call a method of an object inside another class in php?

last week I've started programming in php and now i'm doing my first exercise. I've studied java for two years so i have a good knowledge in computer programming. The exercise asks to create a program that prints lines and rectangles formed with the character "*". Here there's an example:

*****

**

********

**
**
**

*************
*************

***
***
***

Now i know that for the oop paradigm i shouldn't use any println/echo methods in model classes but for this exercise we only wanted to test the differences between php and java so forgive me if the solution of this exercise doesn't seem correct. We have two classes, Line and Rectangle that are very very simple: Line has the task to print a line of length l. Rectangle has to print a rectangle of length l and height h using Line objects.

I have to print lines of length 5,2,8 and rectangles of 2x3, 13x2, 3x3, like in the example. Here there is the code that i have developed so far

SCRIPT CLASS

<?php

require_once 'Linea.php';
require_once 'Rettangolo.php';

$linea1 = new Linea(5);
$linea1->stampaLinea();

$linea2 = new Linea(2);
$linea2->stampaLinea();

$linea3 = new Linea(8);
$linea3->stampaLinea();

$rettangolo = new Rettangolo(2,3);
$rettangolo->stampaRettangolo();

$rettangolo2 = new Rettangolo(13,2);
$rettangolo2->stampaRettangolo();

$rettangolo3 = new Rettangolo(3,3);
$rettangolo3->stampaRettangolo();

CLASS LINE

<?php

class Linea {
    /**
     *
     * @var int
     */
    private $l;

    function __construct($l) {
        $this->l = $l;
    }
    function getLinea() {
        return $this->l;
    }

    function setLinea($linea) {
        $this->l = $linea;
    }

    public function stampaLinea(){
        for ($index = 0; $index < $this->l; $index++) {
            echo "*";
        }
        echo "\n";
    }

}

CLASS RECTANGLE

<?php

class Rettangolo {
    /**
     *
     * @var Linea
     */
    private $linea;
    /**
     *
     * @var int
     */
    private $altezza;

    function __contruct($lunghezza, $altezza){
        $this->linea = new Linea($lunghezza);
        $this->altezza = $altezza;
    }

    function stampaRettangolo(){
        for ($index = 0; $index < $this->altezza; $index++) {
            $this->linea->stampaLinea();
        }
    }
}

The problem is that i can print the lines but not the rectangles. The interpreter gives me this error: Fatal error: Call to a member function stampaLinea() on null in "path of the project" on line 33

Probably there is an error in the method stampaRettangolo in the class Rettangolo but i can't understand what it is.

Upvotes: 0

Views: 72

Answers (1)

Josh J
Josh J

Reputation: 6893

You misspelled __construct in class Rettangolo.

This means that new Rettangolo isn't calling your method so the internal variables are not being set.

Upvotes: 3

Related Questions