-1

I'm wondering how I can include this DateTime function inside a class?

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net

It works outside, but not inside the class.

Glavić
  • 42,781
  • 13
  • 77
  • 107
denski
  • 1,768
  • 4
  • 17
  • 35
  • 2
    It is unclear what you ask. Certainly you can implement any function you want as a method of a class. So the answer to your question simply is: _you just have to do that._ – arkascha Apr 03 '17 at 13:27
  • What do you mean by "It works outside, but not inside the class."? A function / method that "does not work"? How that? – arkascha Apr 03 '17 at 13:27
  • Are you including the file that contains this function anywhere with the class? – segFault Apr 03 '17 at 13:28
  • If your class belongs to a namespace you have to also put `use DateTime` under the namespace declaration. – apokryfos Apr 03 '17 at 13:28
  • It is impossible to answer to a question like this without additional information. It is not at all clear what your actual issue is. You will have to add more information to your question. – arkascha Apr 03 '17 at 13:29
  • In what way ___does it not work in a class___ Show us how you codes it in the class! – RiggsFolly Apr 03 '17 at 13:29
  • _Why does this code not work when I do it some other way_ is really not helping us help you. Please show us how you code this in a class otherwise you are not going to get any answers of any use to you – RiggsFolly Apr 03 '17 at 13:40

2 Answers2

1

To add the function to the class you'd simply do something like:

class myClass {
   public function validateDate($date, $format = 'Y-m-d H:i:s') {
      $d = \DateTime::createFromFormat($format, $date);
      return $d && $d->format($format) == $date;
   }
}

function was copied from this answer or php.net

I've added a \ infront of DateTime just in-case you are namespacing things but you might not need it.

You could then use the function by doing something like:

$myObj = new myClass();
echo $myObj->validateDate($date);
Glavić
  • 42,781
  • 13
  • 77
  • 107
H2ONOCK
  • 956
  • 1
  • 5
  • 19
0
Class myDate {
    // your function
}

$instance = new myDate();
$instance->yourFuncion(yourParameters);
Leandro Papasidero
  • 3,728
  • 1
  • 18
  • 33