0

I got a function who gets all the labels out of the database and puts them into an array, but if I take the object to another function it will be NULL

private static $labels='blaat';

public function loadDatabaseLabels(){
    $res=DB::query("SELECT * FROM labels");
    $label_array=array();
    while($row=mysqli_fetch_assoc($res)){
        $label_array[$row['indicator']]=$row['text'];
    }
    $labels = new label();
    $labels->labels=$label_array;
}

public function getLabel($indicator){
    var_dump($labels->label);
}
1

2 Answers 2

2

It seems that this is a code snippet from a PHP class. If you set a variable as $labels it's in the local method scope, is not seen by anything outside the method and gets lost after method finishes.

To set variables on the object instance, use $this->labels = ... and var_dump($this->labels), or as it's declared static, self::$labels, instead.

If that's not the case then forget about static public private keywords. Functions would still not see anything outside of them tho, so you have an ugly option of adding global $labels in front of the methods (karma will get back at you for this) or passing $labels bu reference to both methods as &$labels.

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

2 Comments

if i use a this i get this error: Using $this when not in object context in
declaring a function as public implies that it exists within a class - otherwise you are using static, public, etc incorrectly.
0

A few issues here. First, $labels is declared private static - this means to access it you would do so using self::$labels:

// set like this:
self::$labels->labels = $labels_array;

public function getLabel($indicator){
    var_dump(self::$labels->label);
}

Secondly, you are not setting self::$lables->label, but self::$labels->labels (note the plural labels). So in the above function, var_dump is accessing something that hasn't been set.

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.