简体   繁体   English

PHP OOP,如何将非静态属性分配给静态方法?

[英]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的静态方法中使用非静态属性,这是错误的代码,但是我想知道如何解决此问题,谢谢

<?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 . 例如,以这些类FirstSecond为例。

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 . 当我们使用Second::getStatic() ,我们将获得Second的实例。
  • When we use Second::getSelf() , we will get an instance of First . 当我们使用Second::getSelf() ,我们将获得First的实例。
  • When we call either method via First , we will get an instance of First . 当我们通过First调用任一方法时,我们将获得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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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