UndefinedReference
UndefinedReference

Reputation: 1253

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.

Upvotes: 0

Views: 65

Answers (6)

Vikas Umrao
Vikas Umrao

Reputation: 2615

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();
?>

Upvotes: 1

someone
someone

Reputation: 6572

You have to change

 benefits = self:$pay;

To

 benefits = self::$pay;  

Upvotes: 0

Ray
Ray

Reputation: 41428

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;

Upvotes: 0

Bot
Bot

Reputation: 11855

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

should be what you are looking for

Upvotes: 0

Chris Miller
Chris Miller

Reputation: 493

inside the benefits function, benefits should be $benefits if you intend to use it as a local variable.

Upvotes: 1

Landon
Landon

Reputation: 4108

I really don't think you want to echo values from that class function. I highly recommend returning 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.

Upvotes: 1

Related Questions