开发者

PHP: Use of static function

i've one stupid question. I keep trying to write my framework, but ... i miss something. I have one base class Base.class.php, with some functions. When, i write another class SubBase.class.php, who extends Base, i trying to set one variable , who must use in Base class, in one stat开发者_StackOverflow中文版ic function (maybe). Something like that

class Base { 
 public $vars;
 public function GetA() { 
  return $this->vars;
 }
}


public SubBase extends Base { 
 public function __construct() { 
  $this->vars = array();
 }
}

But, i missing something ... In role, my SubBase is subpage from my web, Base is printHTML class. I trying to set a title to my web, with my Base class, who set $this->vars in my SubBase class o.O Please, tell me if i'm wrong, and let me know how to write this. I wonna just write

<title> <?php echo Base::GetTitle(); ?> </title>

and show in.


Well, you should take a look at static properties and methods: http://php.net/manual/en/language.oop5.static.php

To accomplish what you want, you can try the following:

class Base { 

   //--------------------------------
   // Declare static property
   public static $title = '';

   //--------------------------------
   // Declare static method
   public static function GetTitle() { 
      return self::$title;
   }
}

public SubBase extends Base { 

   //--------------------------------
   // Construct which overwrites
   // Base::$title
   public function __construct($newTitle){
      self::$title = $newTitle;
   }
}

//--------------------------------
// Instantiate your SubBase object
$subPage = new SubBase($newTitle = 'Welcome to my sub page');

//--------------------------------
// And in your HTML, use
<title> <?php echo SubBase::GetTitle(); ?> </title>

Note, that I used SubBase::GetTitle(); and not Base::GetTitle(); If you use Base::GetTitle(), you're output will be blank because you're using the value given at the Base Class. In my example, its:

public static $title = '';

However, when you instantiate your SubBase class, you provide a "$newTitle" parameter, which then overrides the blank value.

Ideally, this should work. Still, I recommend you learn more about the use of static properties and methods.

Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜