user1743508
user1743508

Reputation: 31

Why is this class property not being modified in PHP?

I have this function:

public userID = 1;

public function setID($id)
    {
        $this->userID = $id;

    }

It's located in a class so this function should set the userID variable on the top. As you can see here I create an object and call the function with the correct parameter:

$data = new Data();
$data->setID(($_SESSION['ID']));

The session ID is indeed available to use I echo'd the session ID.

But now I have another function to use the userID variable and then i get the error:

Undefined variable: userID.

The function I use this variable is this one:

$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

This is in another function below my setID function. Does anyone know how to fix this?

Upvotes: 0

Views: 103

Answers (5)

maechler
maechler

Reputation: 1367

You are missing the $ on your public $userId variable. This example prints 42:

<?php

class Data {
    public $userId = 1;

    public function setId($id) {
        $this->userId = $id;
    }

    public function otherFunction() {
        echo $this->userId;
    }
}

$data = new Data();
$data->setId(42);
$data->otherFunction();

Upvotes: 4

user1743508
user1743508

Reputation: 31

It was posted but deleted again this is the solution :

$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $this->userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

instead of :

$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $userID)";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

Upvotes: 0

Cl&#233;ment Malet
Cl&#233;ment Malet

Reputation: 5090

As the error says, the variable $usedID is not set. The property userId is set though.

You are trying to use a property of the class as a variable, which is not possible. (You may have another variable named $userID, it's quite common in setters for example)

You should always use$this->userId and not $userID.

Upvotes: 0

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

You have to use $this->userID instead of $userID

$ordSql = "INSERT INTO order(DATUM, KLANT_ID) VALUES($datum, $this->userID )";
$resultaat = mysqli_query($verbinding, $sql) or die (mysqli_error($verbinding));

Upvotes: 0

Ayyanar G
Ayyanar G

Reputation: 1545

change

 $userID; 

to

$this->userID;

Upvotes: 0

Related Questions