为什么这个PHP类不起作用

时间:2009-12-08 19:31:15

标签: php

class Browser{

var $type = "";

public function e(){

return $this->type;
}

}

使用时

$b = new Browser('human');

echo $b->e();

我的maen类型没有出现,我把它作为新的ArchiveBrowser(var类型);

4 个答案:

答案 0 :(得分:2)

  • 您不能将“echo”用作函数名称。
  • 你搞乱了一个构造函数。试试这个

class Browser{
    var $type = "";

    function __construct($type){
         $this->type = $type;
    }

    public function echo_type(){
        return $this->type;
   }
}

答案 1 :(得分:1)

echo是保留字。此外,您的班级名为Browser,但您要实例化ArchiveBrowser

答案 2 :(得分:1)

class Browser 
{
   // Always declare whether a variable is public or private
   private $type = null;
   // A constructor - gets excecuted every time you create a class
   public function __construct($type)
   {
      // Note that $type here is not the same as $type above
      // The $type above is now $this->type

      $this->type = $type; // Store the type variable
   }

   // Your function e()
   public function e ()
   {
       return $this->type;
   }

   // __toString() method. (May also be useful)
   // it gets excecuted every time you echo the class, see below.
   public function __toString ()
   {
      return $this->e(); // I chose to return function e() output here
   }

}

用法示例:

$b = new Browser('Human'); // Note, that this executes __construct('Human');
echo $b->e();              // Echos 'Human'

$b = new Browser('Lolcat'); // Excecutes __construct('Lolcat');
echo $b->__toString();      // Echos 'Lolcat'
echo $b;                    // Echos 'Lolcat', equivalent to statement above

//Also:
$c = (string) $b;
echo $c;                    // Echos 'Lolcat'

答案 3 :(得分:0)

ArchiveBrowser应该扩展浏览器,或者你应该使用Browser而不是ArchiveBrowser。