简体   繁体   English

在PHP类的函数之间共享变量

[英]Sharing Variables between functions of a PHP Class

I have code that follows this structure: 我有遵循此结构的代码:

class someClass
{
    private static $pay = 0;

    //something like this...
    public static function run()
    {
        if ($_SESSION['title']== "whatever" and $_SESSION['rank'] == "1")
        {
            self::$pay = 50000;
        }
    }

    public static function benefits()
    {
        self::$pay = 50000 * 1.30;
        benefits = self:$pay;
        echo benefits;
    }
}

Then I try calling benefits like this... 然后,我尝试调用这样的好处...

someClass::benefits();

But it's always set to zero. 但是它始终设置为零。 It never changes when the condition from the if statement is met. 当满足if语句的条件时,它永远不会改变。

Is there something I am doing here that is obviously wrong? 我在这里做的事情显然是错误的吗? I am not getting any errors. 我没有任何错误。

Thank you for your help. 谢谢您的帮助。

I really don't think you want to echo values from that class function. 我真的不认为您想从该类函数中echo值。 I highly recommend return ing then. 我强烈建议您再return And then if you echo them immediately, fine, but you shouldn't echo like that from functions. 然后,如果您立即回显它们,那很好,但是您不应从函数中回显它们。 Without seeing how this is used, that would be my first guess. 不知道如何使用它,那将是我的第一个猜测。

在Benefits函数中,如果打算将其用作局部变量,则Benefits应该是$ benefits。

Try the below code: 试试下面的代码:

<?php
class someClass
{
    private static $pay = 0;

    //something like this...
    public static function run()
    {
        if ($_SESSION['title']== "whatever" and $_SESSION['rank'] == "1")
        {
            self::$pay = 50000;
        }
    }

    public static function benefits()
    {
        self::$pay = 50000 * 1.30;
        $benefits = self::$pay;
        return $benefits;
    }
}

echo someClass::benefits();
?>

You're using benefits as if it was constant (which assignment to is not allowed in php)--you probably mean $benefits . 您正在使用benefits ,就好像它是常量一样(在php中不允许分配给它)-您可能是说$benefits Change your code to this: 将代码更改为此:

    self::$pay = 50000 * 1.30;
    $benefits = self::$pay;
    echo $benefits;
public static function benefits()
{
    self::$pay = 50000 * 1.30;
    echo self::$pay;
}

should be what you are looking for 应该是你要找的

You have to change 你必须改变

 benefits = self:$pay;

To

 benefits = self::$pay;  

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

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