Is it possible to create a "synonym" of a function, two names for the same function?

Asked

Viewed 339 times

3

I own a set of functions using a third-party API. From time to time I thought of making it available, since there is no library publishes in PHP and it makes no difference to keep as a closed source or not. (I’ll still have to change a lot of things.)

However, as I only use such functions, they have strange names and do not match the actual result, and have no prefix. To solve this I thought of simply renaming the functions and include a prefix.

This way all functions would change to:

MinhaApi_*

However, it would be too long to write, so I thought I’d shorten it to:

ma_*

Hence the curiosity:

It is possible to have MinhaApi_* and ma_* simultaneously, without declaring them twice?

So you can understand, instead of using this:

function MinhaApi_text(){
   return 'Isso é um texto';
}

function ma_text(){
   return MinhaApi_text();
}

echo ma_text();

Resultado: Isso é um texto

This works, but requires you to "re-declare" all functions (so I believe it is not the best way).

Wear this:

function MinhaApi_text(), ma_text(){
      return 'Isso é um texto';
}

echo ma_text();

Resultado "esperado": Isso é um texto

That nay works, logically!

  • If I understand correctly gives yes p to give an alias p function, entering you need to use namespaces and in the call( use) give the desired name.

  • @rray, for functions also gives? I thought it was only for classes

  • Yes, now if it’s practical in your case, I don’t know. Taken from documentation: "PHP Namespaces provide a way in which to group Related classes, interfaces, functions and constants"

2 answers

6


  • I didn’t know this feature, it really worked.

  • Really good! I hadn’t found this in my search. Too bad it will only serve for version 5.6, which is absent from most of the hosting servers currently.

1

I did a lot of research and I couldn’t find an alternative. The way you’re doing it is elegant and I use it a lot. I usually use it to make intuitive function names, so that the programmer does not have doubts in the order of the function name, for example:

<?php

function string_convert($var) {
// do something
}

function convert_string($var) {
    return string_convert($var);
}

<?

If you have a PHP file with all the functions (many to be worth) already standardized with functions named as MinhaApi_<algumacoisa>, you can create a PHP script that will open such a file, create and write in a new PHP file the "sisters" functions of those that already exist, assigning the new name and returning the original function. Otherwise, I recommend doing it manually, as you did in the first example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.