PHP OOP,如何将非静态属性分配给静态方法? [英] PHP OOP , How to assign not static property to static method?

查看:48
本文介绍了PHP OOP,如何将非静态属性分配给静态方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下如何在php的静态方法中使用not static属性,这是错误的代码,但我想知道如何解决这个问题,谢谢

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.

这篇关于PHP OOP,如何将非静态属性分配给静态方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆