Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call member variables of a class within a static method?

I am using some method to autoload helper files with functions. The only problem I am having now, is how to call the variables in that class.

Because I am not instantiating it as an object, $this won't work. But what will?

class some_helperclass {

var $some_variable  = '007';

public static function some_func()
    {
    //return 'all ok';
    if (self::some_variable !== FALSE)  
    {
       return  self::ip_adres;
    }
}

I can call the function from anywhere now with the help of spl_autoload_register().

some_helperclass:: some_func();
like image 372
Richard Avatar asked Nov 17 '09 18:11

Richard


People also ask

Can we access class variable in static method?

A static method doesn't have access to the class and instance variables because it does not receive an implicit first argument like self and cls . Therefore it cannot modify the state of the object or class. The class method can be called using ClassName.

How do you access static member variables?

A static member variable: • Belongs to the whole class, and there is only one of it, regardless of the number of objects. Must be defined and initialized outside of any function, like a global variable. It can be accessed by any member function of the class. Normally, it is accessed with the class scope operator.

How can we call a static variable of a class?

Class variables are also known as static variables, and they are declared outside a method, with the help of the keyword 'static'. Static variable is the one that is common to all the instances of the class. A single copy of the variable is shared among all objects.

How do you call a static data member?

A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator ::. A static member function can only access static data member, other static member functions and any other functions from outside the class.


1 Answers

You have to use self::$some_variable. Put the $ in there.

http://www.php.net/manual/en/language.oop5.static.php

The member variable has to be declared static too.

like image 149
Galen Avatar answered Oct 13 '22 01:10

Galen