简体   繁体   中英

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?

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 (eg 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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM