Differentiate between a parameter that can take either file contents or file path in PHP
I'm implementing a function called attach. I'm looking for a way to take a param that is either a file path or a file's contents. Here's what I have:
/**
* @param name - name of the file
* @param file - either a file or a file path
*/
function attach($name, $file) {
$attachment = array();
$attachment['name'] = $name;
if(map($file)) {
$attachment['filepath'] = $file;
$attachment['file'] = file_get_contents($file);
} else {
$attachment['file'] = $file;
$attachment['filepath'] = getcwd();
}
}
/**
* @param filepath - can take multiple forms
* ie. ui:form:text.css => ui/开发者_JAVA技巧form/text.css
* text.css => getcwd().'text.css'
* /ui/form/text.css => /ui/form/text.css
*
* @return if file exists - return file path
* if not found - return false
*/
function map($filepath) {
// ... too long to post
}
The map function allows you to turn namespaces (using ":") into filepaths.
The issue I'm worried about is if an error is made in the filepath (ie. someone types in the file path wrong) I don't want it to think that since the file doesn't exist, it must be file contents
Also: if possible, i'd rather not edit map()
as it would require me to change a bunch of code - consider map as a black box.
Finally: I put this example together quickly - so please do not discuss the shortcomings of getcwd()
, and other syntactical issues. I have a more elaborate system in place in map()
Thanks! Matt Mueller
Even if PHP had better support for method overloading, you'd have a hard time here since both vars (filepath and file contents) would probably be a string. What is preventing you from just creating a couple of wrapper methods, like attach_filepath(..), attach_filecontents(..)? Or, if you are set on having one method, you could add a third param, like:
function attach($name, $file, $filecontents=false) {
I agree that it would probably be a bad idea to try to guess the users' intentions based on the contents of a var that would have the same type in both cases.
Before adding the attachment your code could use a function like file_exists
to determine if what seems like a path actually is a path and the file does in fact exist. Additionally you may want to check if the path refers to a folder or a file.
精彩评论