开发者

why this PHP class is not working

开发者 https://www.devze.com 2022-12-13 17:54 出处:网络
see class Brows开发者_开发问答er{ var $type = \"\"; public function e(){ return $this->type; } } when use

see

class Brows开发者_开发问答er{

var $type = "";

public function e(){

return $this->type;
}

}

when use

$b = new Browser('human');

echo $b->e();

and i maen type not appear and i make it human as new ArchiveBrowser(the var type);


  • You cannot use "echo" as a function name.
  • You are messing a constructor. Try this

.

class Browser{
    var $type = "";

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

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


echo is a reserved word. Also your class is called Browser but you're instantiating ArchiveBrowser.


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
   }

}

Usage examples:

$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'


ArchiveBrowser should extend Browser or You should use Browser instead of ArchiveBrowser.

0

精彩评论

暂无评论...
验证码 换一张
取 消