获取和设置类PHP方法

时间:2015-02-09 11:07:21

标签: php class static

我有这堂课:

<?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";
        }
    }
?>

我想创建这个类的对象,并使用addUser函数分配数据,如下所示:

$test = new Test();
$test:: addUser("Peter", "12"); but I have errors.

我有这个错误:

  

严格标准:非静态方法Test :: addUser()不应该   在第13行的/var/www/public/testManu.php中静态调用

     

严格标准:不应调用非静态方法Test :: setID()   静态地在第18行的/var/www/public/class/Test.php

     

致命错误:在不在对象上下文中时使用$ this   第8行的/var/www/public/class/Test.php

我有可变范围的问题。有人能告诉我这是我的问题????

3 个答案:

答案 0 :(得分:2)

改变这个:

 ...
 public function addUser($name, $age) {
        $this->setID();
        $this->setNAME($name);
        $this->setAGE($age);

        echo "OK";
    }
 ...

调用Classname::function()只对静态方法有效。您有一个专用实例,需要使用构造$this->function()来解决。

因此:

   ...
  $test->addUser("Peter", "12"); but I have errors.

答案 1 :(得分:2)

$test = new Test();
$test -> addUser("Peter", "12"); #now no errors

答案 2 :(得分:1)

这应该适合你:

<?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.
?>