James
James

Reputation: 43

PHP class get method always returns 0

I cannot workout why this script always returns 0. If I change it to echo getSKU() it works, but Quantity, Price or Name never seems to work. If anybody has any ideas please, please help this is irritating the life out of me!

<?php

session_start();

$sku = "0001";
if (!isset($_SESSION[$sku])) {
    $_SESSION[$sku] = new product($sku, 5);
} else {

}

echo $_SESSION[$sku]->getQuantity();

class product {

    var $sku;
    var $name;
    var $price;
    var $quantity;

    function __construct($par1, $par2) {
        $this->sku = $par1;
        $this->quantity = $par2;
    }

    function setSKU($x) {
        $this->sku = $x;
    }

    function getSKU() {
        echo $this->sku;
    }

    function setName($x) {
        $this->name = $x;
    }

    function getName() {
        echo $this->name;
    }

    function setPrice($x) {
        $this->price = $x;
    }

    function getPrice() {
        echo $this->price;
    }

    function setQuantity($x) {
        $this->quantity = $x;
    }

    function incrementQuantity() {
        $this->quantity++;
    }

    function getQuantity() {
        echo $this->quantity;
    }

}

Upvotes: 1

Views: 146

Answers (3)

chris nelson
chris nelson

Reputation: 36

while the issues brought up in the other answers should definitely be addressed, to answer your question i believe the quantity is probably not set. can you try adding this line?

 $_SESSION[$sku]->setQuantity(5);
 $_SESSION[$sku]->getQuantity();

Upvotes: 0

Axcel
Axcel

Reputation: 60

you shouldn't echo your attribute in get methodes

 echo $this->Variable;

you should always return them.

return $this->Variable;

return returns program control to the calling module. Execution resumes at the expression following the called module's invocation

for more information on return check the documentation here

Upvotes: 1

Philipp
Philipp

Reputation: 15629

You should use return instead of echo. Your get...-methods currently don't return something (just implicitly null), they just echo the value you want to return.

To fix this, just replace in every get...-method echo with return - i.e.

function getQuantity() {
    return $this->quantity;
}

In addition to that, you should know, that you cant store objects in $_SESSION (actually you could, but then you have to implement the magic __sleep and __wakeup-methods..). You should think about other solutions to store your products inside the session (i.e. serialize them)

Upvotes: 3

Related Questions