0

I'm new in OOP php and i'm creating add to cart class but count variable is not working inside of add function and it is giving an error: "Notice: Undefined variable: count"

Here is my code :

<?php 
    Class cart{
        public $count=0;

        public function add(){
            @session_start();
            $_SESSION['count'] = $count++;
            echo $_SESSION['count'];
        }

        public function check(){
            if(isset($_POST['sub'])){
                $this->add();
            }
        }
    }

    $obj = new cart;
    $obj->check();
?>

2 Answers 2

2

Class property can be accessed with this keyword

 $_SESSION['count'] = $this->count++;

Read more about php variable scope

Sign up to request clarification or add additional context in comments.

Comments

0

You have to use

$_SESSION['count'] = $this->count++;

instead of

$_SESSION['count'] = $count++;

Notes:

1) If $count should not be accessible outside your class you should change the declaration to private $count=0;.

2) Do you really need property $check? In your current case you can remove $check property and use $_SESSION['count'] = isset($_SESSION['count']) ? $_SESSION['count']++ : 0 in your add method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.