0

I need to assign b value in a inside the method onec, but its failing. Please let me know what I am doing wrong here:

<?php

class One {

    public $a = 10;
    public $b = 20;

    public static function onec() {
        $this->a = $this->b;
        return $this->a;
    }

}

echo One::onec();

?>
1

3 Answers 3

4

Use the self keyword. The $this keyword is not accessible under static context. Also, you should make your variables static

Like this..

<?php

class One {

    public static $a = 10;
    public static $b = 20;

    public static function onec() {
        self::$a = self::$b;
        return self::$a;
    }

}
echo One::onec();
Sign up to request clarification or add additional context in comments.

Comments

0

You use $this in static function. http://www.php.net/manual/en/language.oop5.static.php

<?php

class One {

    public $a = 10;
    public $b = 20;

    public static function onec() {
        $obj = new One();
        $obj->a = $obj->b;
        return $obj->a;
    }

}

echo One::onec();

Comments

0

Use this code

class One {
   public $a = 10;
   public $b = 20;

   public function onec() {
     $this->a = $this->b;
     return $this->a;
   }
}
$obj = new One();
echo $obj->onec();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.