user4012084
user4012084

Reputation:

Global variables in classes laravel 4

I have something like this

class Unilevel {

    public $contador = 2;

    public static function listarLevels($user_id){
        if($contador <= 5){
            echo '<h1>Nivel '.$contador.'</h1>';

            $user = DB::table('matrices')->where('id_user', $user_id)->first();

            $actual_user =  DB::table('users')->where('id', $user->id_user)->first();
            echo  $actual_user->username.'<br>'; 
        }

        $contador++;
    }
}

The function is not working but if i put the variable $contador inside listarLevels works which is the problem? Thanks

Upvotes: 0

Views: 4920

Answers (2)

Sher Afgan
Sher Afgan

Reputation: 1234

You can't access your class non static properties in static methods.

Try this.

class Unilevel {

    public static $contador = 2;

    public static function listarLevels($user_id){
             //self::$contador = 4;
    }
}

If your method is static you need make your property static too. Their are few other ways too like instantiating the object of the class. Read more about static in PHP.

Upvotes: 0

user1669496
user1669496

Reputation: 33058

This is how classes work in PHP.

To call $contador within the function when you've declared it as a class property, you use $this->contador

It may be helpful to read the manual on object oriented programming in PHP to get more familiar with it before diving into Laravel. http://php.net/manual/en/language.oop5.php

Upvotes: 3

Related Questions