Amiga
Amiga

Reputation: 693

Calling for a function within a function from another class returns "0"

<?php
class Kunde 
{
    public $knr;
    public $navn;
    public $adr;
    public $tlfnr;
    public $kurv = array();

    function __construct($nr,$n,$a)
    {
        $this->knr = $nr;
        $this->navn = $n;
        $this->adr = $a;
    }

    function LeggTilVare($vnavn,$vantall,$vpris)
    {
        $this->kurv[]=new Vare($vnavn,$vantall,$vpris);
    }

    function VisVarer()
    {
        for($i=0; $i < count($this->kurv); $i++)
        {
            $text+= $this->kurv[$i]->getInfo() . "<br/>";
        }

        return $text;
    }

class Vare 
{
    public $varenavn;
    public $antall;
    public $pris;

    function __construct($navn,$antall,$pris)
    {
        $this->varenavn=$navn;
        $this->antall=$antall;
        $this->pris=$pris;
    }

    function getInfo()
    {
        return $this->varenavn.", ".$this->antall." st, ".$this->pris.",-";
    }
}

$kunde1 = new Kunde(1,"Andreas","Gronland");

$kunde1->LeggTilVare("Kjekks", 10, 10.00);

I'm used to programming in Java but am now learning PHP.

My function VisVarer() will just return "0" and nothing else. I guess it has to do with the call for getInfo() inside another function from another class, or somethings wrong with my for-loop.

Maybe this is the wrong way to program something like this?

echo $kunde1->kurv[0]->getInfo(); // returns "Kjekks, 10 st, 10"

echo $kunde1->VisVarer(); // returns "0"

Upvotes: 0

Views: 77

Answers (5)

Sol
Sol

Reputation: 889

Change this line to

$text.= $this->kurv[$i]->getInfo() . "<br/>";

the concatenation assign operator in PHP is .= not +=. What is happening is that you are adding as a number the resulting string to $text so it will always be zero.

Upvotes: 0

String concatenation is done with ., not +.

As such, you want to do .= instead of += in VisVarer.

Upvotes: 0

Evert
Evert

Reputation: 99533

You are using this operator:

+=

That's only used for integers. PHP will try to turn the string into an integer (which ends up being 0).

Instead, you probably want the string concatenation operator:

.= 

Upvotes: 0

leftclickben
leftclickben

Reputation: 4614

You are using the += operator when you should use the .= operator for string concatenation.

In PHP, these are two different operations, mathematical addition and string concatenation.

Upvotes: 2

mishu
mishu

Reputation: 5397

In php the concatenation operator is the dot In this line:

$text+= $this->kurv[$i]->getInfo() . "<br/>";

you are using the one you are used to from java (+=) and also the php specific one, the dot

try changing that line (and all those similar) to

$text .= $this->kurv[$i]->getInfo() . "<br/>";

Upvotes: 2

Related Questions