简体   繁体   中英

PHP OOP , How to assign not static property to static method?

could someone explain how to use not static property in static method in php, this is wrong code, but i want to know how to fix this, thank you

<?php
class SomeClass
{
    public $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

echo SomeClass::getSomethingStatic();
?>

You can't directly. You need to create an object instance. You can make one and pass it to a static method, or make one in static method's body.

Regular (non-static) properties require object instance of given class (type). Static methods are called by referring to the class itself, not an object.

You can however use static properties or constants for static methods needs without creating object instance at all.

You have to instantiate object

<?php
class SomeClass
{
    public $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        $object = new self();
        return $object->_someMember * 5; // here's the catch
    }
}

echo SomeClass::getSomethingStatic();

You can statically create an instance of the class that the method is being called on via:

$instance = new static();

You can also statically create instances of the class that actually defines the method via:

$instance = new self();

As an example, take these classes First and Second .

class First
{
    public static function getStatic()
    {
        return new static();
    }

    public static function getSelf()
    {
        return new self();
    }
}


class Second extends First{ }
  • When we use Second::getStatic() , we will get an instance of Second .
  • When we use Second::getSelf() , we will get an instance of First .
  • When we call either method via First , we will get an instance of First .

This means you can change your method to:

public static function getSomethingStatic()
{
    $instance = new static(); // or new self() if you always want to use 'SomeClass'
                              // and never an extending class.

    return $instance->_someMember;
}

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