[英]Class PHP methods get and set
I have this class: 我有这个课:
<?php
class Test {
private $_ID;
private $_NAME;
private $_AGE;
public function setID() { $this->_ID++; }
public function getID() { return $this->_ID; }
public function setNAME($element) { $this->_NAME = $element; }
public function getNAME() { return $this->_NAME; }
public function setAGE($element) { $this->_AGE = $element; }
public function getAGE() { return $this->_AGE; }
public function addUser($name, $age) {
Test::setID();
Test::setNAME($name);
Test::setAGE($age);
echo "OK";
}
}
?>
I want to create objects of this class, and assign the data with the function addUser like this: 我想创建此类的对象,并使用以下函数addUser分配数据:
$test = new Test();
$test:: addUser("Peter", "12"); but I have errors.
I have this errors: 我有这个错误:
Strict Standards: Non-static method Test::addUser() should not be called statically in /var/www/public/testManu.php on line 13
严格标准:非静态方法Test :: addUser()不应在第13行的/var/www/public/testManu.php中被静态调用
Strict Standards: Non-static method Test::setID() should not be called statically in /var/www/public/class/Test.php on line 18
严格标准:非静态方法Test :: setID()不应在第18行的/var/www/public/class/Test.php中被静态调用
Fatal error: Using $this when not in object context in /var/www/public/class/Test.php on line 8
致命错误:第8行的/var/www/public/class/Test.php中不在对象上下文中时使用$ this
I have problems with variable scope. 我有可变范围的问题。 Could somebody tell me what it is my problem????
有人可以告诉我这是我的问题吗????
change this: 改变这个:
...
public function addUser($name, $age) {
$this->setID();
$this->setNAME($name);
$this->setAGE($age);
echo "OK";
}
...
Calling like Classname::function()
is only valid for static methods. 像
Classname::function()
这样的调用仅对静态方法有效。 You have a dedicated instance which need to be addressed with the construct $this->function()
. 您有一个专用实例,需要使用构造
$this->function()
。
And thus: 因此:
...
$test->addUser("Peter", "12"); but I have errors.
$test = new Test();
$test -> addUser("Peter", "12"); #now no errors
This should work for you: 这应该为您工作:
<?php
class Test {
private static $_ID = 1;
private static $_NAME;
private static $_AGE;
public static function setID() { self::$_ID++; }
public static function getID() { return self::$_ID; }
public static function setNAME($element) { self::$_NAME = $element; }
public static function getNAME() { return self::$_NAME; }
public static function setAGE($element) { self::$_AGE = $element; }
public static function getAGE() { return self::$_AGE; }
public static function addUser($name, $age) {
self::setID();
self::setNAME($name);
self::setAGE($age);
echo "OK";
}
}
$test = new Test(); /*You don't need to instantiate the class
because you're calling a static function*/
$test:: addUser("Peter", "12"); but I have errors.
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.