Reference problems with PHP classes

Source: Internet
Author: User
Class calculate{
var $var 1=10;
var $var 2=2;
function Add () {
return $this->var1+ $this->var2;
}
function Subtract () {
return $this->var1-$this->var2;
}
function multiplication () {
return $this->var1* $this->var2;
}
}
Class a{
Function ex () {
return Calculate::add ();
}
}
$a = new A;
echo $a->ex ();
?>
Why is the return of 0?


Reply to discussion (solution)

When you statically access a class method, you can only return 0 because the $this is not available
It's good to have no error.

Function ex () {
$t = new Calculate;
return $t->add ();
}
This will return 12.


such as the owner of the moderator or can
Class calculate{
Static $var 1=10;
Static $var 2=2;
function Add () {
Return self:: $var 1+self:: $var 2;
}

}
Class a{
Function ex () {
return Calculate::add ();
}
}
$a = new A;
echo $a->ex ();

Or you can do this:
Define methods and properties as static, which you do not need to instantiate to access.

Class calculate{
static public $var 1 = 10;
static public $var 2 = 2;

public static function add () {
Return self:: $var 1 + self:: $var 2;
}
public static function subtract () {
Return self:: $var 1-self:: $var 2;
}
public static function multiplication () {
Return self:: $var 1 * Self:: $var 2;
}
}
Class a{
Function ex () {
return Calculate::add ();
}
}
$a = new A;
echo $a->ex ();
?>

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.