【问题标题】:Simple class using php使用php的简单类
【发布时间】:2011-04-22 09:50:41
【问题描述】:

你好,我是 PHP 新手,我需要帮助来了解 PHP 类的基础知识。

我想要一个使用私有公共保护和静态的类的示例。
以及它们是如何工作的..

提前致谢。

哦,我也忘记了如何扩展。 我在谈论父母和孩子的东西或什么.. 再次感谢。

【问题讨论】:

  • 我认为您应该先阅读教程,然后在遇到实际问题时再回来!目前你基本上是在说“我对 PHP 类一无所知,也没有努力学习任何东西”。如果您有不明白的地方,请尝试并提出具体问题。
  • @adamnfish 哎哟,我们应该帮助新用户了解要问的问题类型。但我必须同意提出具体问题
  • @Phill Pafford 我认为这正是@adamnfish 的意思。简洁的语气并不意味着这个人没有帮助。:)
  • @Phill @Zilch 为我的粗鲁回应道歉,祝教程好运 :)
  • 你应该回答你的问题

标签: php class static protected extends


【解决方案1】:

绝对同意其他人的观点。您应该阅读 5.5 亿份在线 PHP 手册,包括其他答案中提供的链接。与此同时,你得到了这个:

class one {
   private $name;
   const ONE = 'ONE';

   // php magic function.  allocate memory for object upon instantiation
   // called with new
   public function __construct($name = null) {
      $this->init($name);
   }

   protected function name() {
      return $this->name;
   }

   // php magic function called when object variable is accessed in a string context
   public function __toString() {
      return __CLASS__ . ': ' . $this->name;
   }

   // static functions can be called without instantiation
   public static function con() {
      echo self::ONE;
   }

   private function init($name) {
      $this->name = $name;
   }
}


// two cannot overwrite method init() -- it is private.
// two has no access to $name.  It is private in one and not visible to two
class two extends one {
   // protected methods can be overwritten
   protected function name() {
      return parent::name();
   }
   // so can public methods
   public function __toString() {
      return __CLASS__ . ': ' . $this->name();
   }
}

// static method call; no instantiation needed
echo one::con() . "\n"; // ONE
// public methods can be called by child class
echo two::con() . "\n"; // ONE
$one = new one('uno');
echo "$one\n"; // one: uno
$two = new two('dos');
echo "$two\n"; // two: dos
$one->name(); // bork! No public access to this method

【讨论】:

    【解决方案2】:
    【解决方案3】:
    【解决方案4】:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-29
      • 2018-09-12
      • 2013-09-06
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 2015-04-15
      • 2017-11-29
      相关资源
      最近更新 更多