简体   繁体   中英

Can I create new functions for PHP default classes like javascript?

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?

No, but you can extend the class and useimport 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.

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

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();


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM