Austin
Austin

Reputation: 47

PHP undefined index in a class

I know this has been asked before and I have looked at multiple threads on why this would happen but could not understand how mine does not work as other variables defined in the same way and gathered the same way work.

class item{
    var $name = "test";
    var $id = 3;

    function setId($newID){
        global $id;
        $id = $newID;
    }

    function getId(){
        return $GLOBALS['id'];
    }

    function setName($newName){
        global $name;
        $name = $newName;
    }

    function getName(){
        return $GLOBALS['name'];
    }
}

That is a snippet of the class as it is really long but duplicate getName and setName for 5/6 more items.

$item[0]->getName();

Would return "test"

$item[0]->getId();

Returns the "Undefined index: id in link to file on line 59" which is the getId() function.

Every function other then getId() works and I have no idea why

EDIT - this question has been answered I am waiting to be able to accept an answer. $this worked for the variable to return (even though I'm still not sure why it would even though the 5 or 6 others would)

Upvotes: 1

Views: 2237

Answers (3)

Steven Johnston
Steven Johnston

Reputation: 1849

Not sure if this helps but I can't tell if you initialized the class at all.

<?php
class Item{   //Use Capital for class name
    var $name = "test";
    var $id = 3;

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

    function getId(){
        return $this->id;
    }

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

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

Then this is how you get name

$item = new Item(); //initialize 
$item->getName(); //get name

Upvotes: 0

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

Your understanding of variable scope within a class is wrong. Setters and getters are, usually, to modify and fetch private or protected properties. Assigning a property with var automatically gives them a public scope.

In a class, you don't need to use global - in fact, using global is bad practice anyway. You can reference class properties with $this.

For example;

class item {
    private $name = "test";
    private $id = 3;

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

    function getId(){
        return $this->id;
    }

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

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

Upvotes: 5

degr
degr

Reputation: 1565

  1. Start your classes from large letter (and use camelCase for variables and CamelCase for classes):

    class Item

  2. Do not use var $id inside of your class, use private or protected access modifiers:

    private $id;

  3. Access your class variables using $this:

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

Hope it will help

Upvotes: 0

Related Questions