简体   繁体   中英

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.

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. I highly recommend return ing then. 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 . 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;  

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