-1

In Javascript has the Class named Date and I can created a custom function for it:

Date.prototype.day = function (value) {...}

Can I create functions like this in PHP default classes like DateTime, without developing new child classes?

3 Answers3

1

No, but you can extend the class and use import aliases.

use MyDateTime as DateTime;

class MyDateTime extends \DateTime {
    public function foo() {
        echo 'hello world';
    }
}

$d = new DateTime();
$d->foo();

However, imports are per-file, so you'd need to add that use statement to every file in which you want to do this.

Honestly, it would make more sense to just use your own class without the alias.

Sammitch
  • 30,782
  • 7
  • 50
  • 77
0

You can do this, but you shouldn't.

It's called monkey patching and it can be achieved with php's runkit library, esp. with runkit7_method_redefine. See this answer to a similar question.

However, I find this approach very dirty. It's always better to make your own class.

class MyDateTime extends DateTime {
  function day() {
    return $this->format('d');
  }
}

$date = new MyDateTime('2020-01-01');
echo $date->format('Y-m-d') . "\n";   // 2020-01-01
echo $date->day() . "\n";             // 01
ΔO 'delta zero'
  • 3,506
  • 1
  • 19
  • 31
0

You can use namespace in PHP

So you do your logic code like this

<?php
namespace AnyName;
Class DateTime{
...
}

Then In the script where you want to use the function, you require() the class file (logic code) and import the namespace by using the use keyword

Like this

<?php
require ('directory/file/....php');
use AnyName\DateTime;
$variable= new DateTime();


ket-c
  • 211
  • 1
  • 10