我尝试使用静态方法(我不想实例化一个类)。我举了这个例子。
<?php
class RootClass {
const Member = 20;
public static function Member() {
return self::Member;
}
}
class NewClass {
private $ValNewClass = "";
private function InitNewClass() {
$this->ValNewClass = RootClass::Member();
}
public static function GetNewVal() {
$this->InitNewClass();
$Validation = true;
if ($this->ValNewClass>10){
echo "greater than 10";
$Validation = false;
} else {
echo "Not greater than 10";
}
return $Validation;
}
}
$Val2 = NewClass::GetNewVal(); //It must print "greater than 10"
?>
我需要知道我的错误在哪里。这不是真正的代码,只是简单的询问形式。
谢谢。
在 PHP 中,$this 变量在声明为 static 的方法中不可用。
不能在静态方法中引用非静态字段。此类类中的值不能与对象相关。当您使用 $this->field 时,您引用的是类实例中的值。如果要修改静态字段,则应使用 self::field。
<?php
class Rootclass {
const MEMBER = 20;
public static function member() {
return self::MEMBER;
}
}
class Newclass {
private static $valnewclass = "";
private function initnewclass() {
self::$valnewclass = Rootclass::member();
}
public static function getnewval() {
self::initnewclass(); //Initialice Val for make comparation
$validation = true;
if (self::$valnewclass>10){
echo "<br>greater than 10";
$Validation = false;
} else {
echo "<br>Not greater than 10";
}
return $validation;
}
}
$Val2 = Newclass::getnewval(); //It must print "greater than 10"
echo "<br>After";
?>
谢谢代码正在工作。
切佩。