wright67uk Posted April 7, 2012 Share Posted April 7, 2012 Im exploring the world of classes, methods and objects and im after some explanation to my code below; 1) what does echo $oTime->sTime; do in this code. 2) why do i NOT need to add "$sTime =" before "$oTime->ShowFutureDate(20); " for the code to execute properly (as i did in line time.php <?php include('class_time.php'); //include file where class is stored $oTime = new Time; // VARIABLE = new CLASSNAME $oTime is now the object variable $sTime = $oTime->GenerateCurrentTime(); // use GenerateCurrentTime within the $oTime class // -> means 'is the parent of' $oTime is the parent of ' GenerateCurrentTime()' print 'The time is: ' . $sTime; // print value of GenerateCurrentTime echo $oTime->sTime; echo "<br/>"; // new line $oTime->ShowFutureDate(20); print 'The future time is: ' . $sTime; echo $oTime->sTime; ?> class_time.php <?php class Time { var $stime; function GenerateCurrentTime() { $this->sTime = gmdate("d-m-Y H:i:s"); //assign the current date to the sTime variable } function ShowFutureDate($iAddDays=0) { $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days")); } } ?> Quote Link to comment https://forums.phpfreaks.com/topic/260523-object-classes-and-moustaches/ Share on other sites More sharing options...
KevinM1 Posted April 7, 2012 Share Posted April 7, 2012 You're confusing yourself because the class code is written in PHP 4 syntax (the var keyword). That leads to the $sTime member variable being public, and, since you also have an $sTime local variable in play, things are getting muddled. Use PHP 5 syntax instead: class Time { private $sTime; function GenerateCurrentTime() { $this->sTime = gmdate("d-m-Y H:i:s"); //assign the current date to the sTime variable } function ShowFutureDate($iAddDays=0) { $this->sTime = gmdate("d-m-Y H:i:s", strtotime("+" . $iAddDays . " days")); } } That might make things more clear. Also, get this book: http://www.amazon.com/Objects-Patterns-Practice-Experts-Source/dp/143022925X/ref=sr_1_1?s=books&ie=UTF8&qid=1333840120&sr=1-1 Finally, -> does not mean 'parent of'. I don't know where you got that idea, but it's wrong. -> is the 'to member' operator, meaning that with $oTime -> GenerateCurrentTime(), you're accessing the member function/method named GenerateCurrentTime of the Time object referenced by the variable $oTime. Quote Link to comment https://forums.phpfreaks.com/topic/260523-object-classes-and-moustaches/#findComment-1335263 Share on other sites More sharing options...
ignace Posted April 8, 2012 Share Posted April 8, 2012 There really is no need to create your own Time object as PHP has a built-in equivalent DateTime Quote Link to comment https://forums.phpfreaks.com/topic/260523-object-classes-and-moustaches/#findComment-1335331 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.