Martin AJ
Martin AJ

Reputation: 6697

How can I access a property out of the static method?

Here is my code:

class {
    $property = "something";
    public static function myfunc() {
         return $this->property;
    }
}

but PHP throws this:

Using $this when not in object context

I know, the problem is using $this-> in a static method, ok I remove it like this:

class {
    $property = "something";
    public static function myfunc() {
         return self::property;
    }
}

But sadly PHP throws this:

Undefined class constant 'property'

How can I access a property which is out of a static method in it?

Upvotes: 3

Views: 4188

Answers (2)

Amin NAIRI
Amin NAIRI

Reputation: 2504

Explaination

If you want to use a variable that wont change inside a class you don't want to instanciate, you need to use the static keyword in order to access it later in a method.

Also, you need a name for your class.

And finally, if you didn't specify a keyword as protected or public, you variable may be accessible outside the word, and so the method would be pointless. So I assume you need a protected value in order to use the method to call that variable.

Source-code

class Foo {

    protected static $property = 'something';

    public function getProperty() {

        return self::$property;

    }

}

echo Foo::getProperty(); /* will display : something */
echo Foo::$property; /* change from protected to public to use that syntax */

Documentation

PHP : classes.

PHP : static.

PHP : visibility.

Upvotes: 2

Yury Fedorov
Yury Fedorov

Reputation: 14928

Generally, you should not do it. Static methods don't have an access to instance fields for a reason. You can do something like this, though:

// define a static variable
private static $instance;

// somewhere in the constructor probably
self::$instance = $this;

// somewhere in your static method
self::$instance->methodToCall();

Note that it will work only for a single instance of your class, since static variables are shared between all instances (if any).

You'll also need to add a bunch of validations (e.g. is $instance null?) and pay attention to all the implementation details that may cause you some troubles.

Anyway, I don't recommend this approach. Use it at your own risk.

Upvotes: 7

Related Questions