Home > Backend Development > PHP Tutorial > php类的引用问题

php类的引用问题

WBOY
Release: 2016-06-23 14:08:38
Original
919 people have browsed it

class calculate{
var $var1=10;
var $var2=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();
?>
为什么返回的是0呢?


回复讨论(解决方案)

静态访问类方法时,由于 $this 不可用,所以只能返回 0
没有报错就已经很好了

function ex(){
  $t = new calculate;
  return $t->add();
}
这样才会返回 12


如版主所主 或可以这样
class calculate{
static $var1=10;
static $var2=2;
function add(){
return self::$var1+self::$var2;
}

}
class A{
function ex(){
return calculate::add();
}
}
       $a = new A;
       echo $a->ex();

或者可以这样:
把方法和属性都定义为 static,不需要实例化就可以访问的

class calculate{
static public $var1 = 10;
static public $var2 = 2;

public static function add(){
return self::$var1 + self::$var2;
}
public static function subtract(){
return self::$var1 - self::$var2;
}
public static function multiplication(){
return self::$var1 * self::$var2;
}
}
class A{
function ex(){
return calculate::add();
}
}
       $a = new A;
       echo $a->ex();
?>

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template