简体   繁体   English

PHP-带有变量的函数名

[英]PHP - Prepending Function Name with Variable

I'm in the middle of creating a fairly large system that incorporates many different files (about 300 at this point). 我正在创建一个包含许多不同文件的大型系统(目前大约300个文件)。 I've created a file to hold various user-defined functions. 我创建了一个文件来保存各种用户定义的函数。

I've begun to think that it would have been best to add a prefix to each function name so as to not have an inadvertent conflict with a previously defined function. 我开始认为最好在每个函数名称上添加一个前缀,以免与先前定义的函数发生意外冲突。 For example... 例如...

My Function: function add_value() 我的功能: function add_value()
With Prefix: function PREFIX_add_value() 带前缀: function PREFIX_add_value()

For the PREFIX_ part I was thinking I could create a variable so the prefix could be easily changed in the future if necessary. 对于PREFIX_部分,我想我可以创建一个变量,以便将来可以根据需要轻松更改前缀。 So, maybe something like this... 所以,也许像这样...

$func_prefix = 'package_name';
function $func_prefix . add_value()

This doesn't work though. 但是,这不起作用。

So, is there a best practice about how to name/prepend functions so as to avoid conflicts within a system with many files? 因此,是否有关于如何命名/添加函数的最佳实践,以避免在包含多个文件的系统中发生冲突?

BTW, I have PHP 5.2.17 on my shared hosting plan. 顺便说一句,我的共享托管计划上有PHP 5.2.17。

Usage: 用法:

<?php

$func_prefix = 'package_name'; 
$name = $func_prefix . '_add_value';
$name();// call package_name_add_value();

You are trying to solve a problem that need not exist. 您正在尝试解决一个不存在的问题。 You are not the first to come across this problem, and many paradigms have been created. 您不是第一个遇到此问题的人,并且已经创建了许多范例。 This is the world of software design. 这就是软件设计的世界。

I mean this with the best intent, but if you have a project of 300 files, and have asked this question without considering an Object Oriented approach, then the only positive I can give you is that one day you will look back on this project with a slight amount of disbelief. 我的意思是最好的,但是如果您有一个300个文件的项目,并且在问这个问题时没有考虑面向对象的方法,那么我能给您的唯一积极的看法就是,有一天您将回头来看这个项目有点难以置信。

I would suggest that you learn and Object Oriented programming at a basic level. 我建议您从基本的角度学习和面向对象的编程。 Java, C++, PHP, it won't matter, but read and experiment. Java,C ++,PHP,没关系,但请阅读并进行实验。 And then consider what 'objects' you can identify in your project. 然后考虑您可以在项目中识别哪些“对象”。

Namespaces exist to prevent conflict, but don't worry too much about that right now. 存在命名空间是为了防止冲突,但是现在不必为此担心太多。 I suspect that if you build the correct objects in your code , your conflicts may disappear. 我怀疑如果您在代码中构建正确的对象,则冲突可能会消失。

That said, the following code, albeit 'ugly', should go towards solving your problem 也就是说,以下代码虽然“丑陋”,但应该可以解决您的问题

function file1_foo(){
    ....
}

$prefix = 'file1_';
$function = $prefix.'foo';
$function();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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