@Daniel Saad,謝謝你幫助我理解。這是解決我的問題:
class Date{
private $dateString;
function __construct($dateString)
{
$this->dateString = $dateString;
}
// Method to display date in different formats.
public function displayDate($dateFormat)
{
list($day, $month, $year) = explode('-', $this->dateString);
switch($dateFormat)
{
case "YYYY-mm-dd" : $format = $year.'-'.$month.'-'.$day; break;
case "mm-dd-YYYY" : $format = $month.'-'.$day.'-'.$year; break;
default : $format = $year.'-'.$month.'-'.$day;
}
return $format;
}
//Method to get day
public function day()
{
$day = date('d', strtotime($this->dateString));
return $day;
}
//Method to get the day of the week.
public function dayofweek()
{
$weekday = date('l', strtotime($this->dateString));
return $weekday;
}
//Method to get month in text.
public function getmonth()
{
$month = date('F', strtotime($this->dateString));
return $month;
}
}
?>
的index.php
<?php
//Initialisation
$date = new Date('14-01-2014');
$anotherdate = new Date('13-07-1979')
?>
<h3>Instance 1</h3>
<p>Date: <?php echo $date->displayDate('YYYY-mm-dd'); ?></p>
<p>Day: <?php echo $date->day(); ?></p>
<p>Day of week: <?php echo $date->dayofweek(); ?></p>
<p>Month: <?php echo $date->getmonth(); ?></p> <br />
結果: 實例1 日期:2014年1月14日 日:本週14 日:星期二 月份:1月
我希望這也可以幫助那些誰是剛開始瞭解OOP。
爲什麼不看看[DateTime對象](http://www.php.net/manual/en/class.datetime.php)和[格式](http://www.php.net/ manual/en/datetime.format.php)方法 –
看來你並不清楚函數,類,對象和方法之間有什麼區別。我建議你先學習一些理論。查找一些基本的OOP教程。 – s3v3n
@ s3v3n我問這個問題是因爲我想學習理論,我也檢查了一些教程。 – swissed