Jump to content

I Need Help Understanding Some Strange PHP code!


mmtalon

Recommended Posts

I need help with understanding the following PHP code:

[color=red][b]$functionName = 'ImageCreateFrom' . $this->type;[/b][/color]

The code is part of a class function. A copy of the function is below and the code in question is above highlighted in red and bold.

After this assignment, the code checks to see if a function "$functionName" exist and later assigns a class variable with the value of the "$functionName(class var)" function call.

The dollar sign in front of the function seems strange to me.

Q. can you create a function in this manner?

Please help me understand and tell me where I can go to get more information with this code assignment.

Thanks All.
[code]
function load($image)
    {
        $this->uid = md5($_SERVER['REMOTE_ADDR']);
        $this->image = $image;
        $this->_get_image_details($image);
        $functionName = 'ImageCreateFrom' . $this->type;

if(function_exists($functionName))
{
$this->imageHandle = $functionName($this->image);
}
    } // End load

[/code]

Link to comment
Share on other sites

Yup, that's perfectly valid. From the php manual on [url=http://www.php.net/image]Image functions[/url], you'll see that there are a whole bunch of functions:

imagecreatefromgd2 -- Create a new image from GD2 file or URL
imagecreatefromgd2part -- Create a new image from a given part of GD2 file or URL
imagecreatefromgd -- Create a new image from GD file or URL
imagecreatefromgif -- Create a new image from file or URL
imagecreatefromjpeg -- Create a new image from file or URL
imagecreatefrompng -- Create a new image from file or URL
imagecreatefromstring -- Create a new image from the image stream in the string
imagecreatefromwbmp -- Create a new image from file or URL
imagecreatefromxbm -- Create a new image from file or URL
imagecreatefromxpm -- Create a new image from file or URL

What the class is aiming to do is avoid from having to hardcode all the different functions for all the different image types supported. What I gather will happen is that $this->type will contain a value such as "jpeg", "png", "gif", etc. The result will be for example $functionName = 'ImageCreateFromJPEG'.

function_exists will make sure that the function, ie ImageCreateFromJPEG, actually exists. If you had a PSD, it would try and do a ImageCreateFromPSD, which doesn't exist and will fail if called, so this is to make sure you're ok. (Not sure what will happen later on in the class if this check fails)

The $functionName($this->image) statement is perfectly valid. it will evaluate $functionName to, as in the running example, ImageCreateFromJPEG, which will then turn the actual function call into ImageCreateFromJPEG($this->image).

Note that the same works for variable names:
[code]
$a = "b";
$b = "Bob";
print $$a;
[/code]
will print "Bob", since the "$a" will evaluate to "b", and then the "$b" will evaluate to "Bob". Try it!

Same works with functions:
[code]
$a = "myNameFunc";
function myNameFunc($name){
  return "Bill and $name";
}
echo $a("Alice");
[/code]
will print out "Bill and Alice"
Link to comment
Share on other sites

Thank you for your help KingPhilip.

[quote]Okay, are you wanting to make functionName a function or a variable?

because right now you have it set as a variable, but then checks to see if it is a function. [/quote]

Is "$functionName" setup as a variable? If I can recall playing around with C++, this code could be acting as a pointer to the beginning of the function and copying another function to create a duplicate. Nevertheless, I never seen a function called using a pointer and parameters. I could be totally off base here, and that is why I am asking. But I am assuming that the developers are creating a function and is using function_exists call as an error handler.

This is not the only time I have seen this code being used. I got the code example that I posted from the Xinha site [url=http://(http://xinha.python-hosting.com/changeset/622?format=diff)](http://xinha.python-hosting.com/changeset/622?format=diff)[/url], the HTML open source editor.

Here's another example below that came from Drupal Developers [url=http://(http://cvs.drupal.org/viewcvs/drupal/contributions/sandbox/jareyero/image/image.gd2.inc?rev=1.2)](http://cvs.drupal.org/viewcvs/drupal/contributions/sandbox/jareyero/image/image.gd2.inc?rev=1.2)[/url], the web-based content management system. This example was not part of a class, however, it's using the same concept.

[code] // Check image type
 $image_details = _get_image_details($imagename);
 $function = 'imageCreateFrom'.$image_details['type'];
 if (function_exists($function))  {
   $im = $function($imagename);
[/code]

Please do reply, KingPhilip, if you have the time, especially if I'm wrong about the pointer assumption. Thank you again for your consideration.

P.S. I just read MCP's Post before posting this reply.

[quote]What the class is aiming to do is avoid from having to hardcode all the different functions for all the different image types supported.[/quote]

[quote]The $functionName($this->image) statement is perfectly valid. it will evaluate $functionName to, as in the running example, ImageCreateFromJPEG, which will then turn the actual function call into ImageCreateFromJPEG($this->image).
[/quote]

I will research this further because I am still in doubt regarding thoughts about this as mentioned above. So MCP, if you read this, please don't hesitate to respond.

Thank you all so much for your time and clearification.



Link to comment
Share on other sites

MCP,

This makes a lot of sense and possibly ties into my pointer theory. Thank you for pointing this snippet of code out to me, no pun intended.

[quote]Note that the same works for variable names:

Code:
$a = "b";
$b = "Bob";
print $$a;
will print "Bob", since the "$a" will evaluate to "b", and then the "$b" will evaluate to "Bob". Try it!

Same works with functions:

Code:
$a = "myNameFunc";
function myNameFunc($name){
  return "Bill and $name";
}
echo $a("Alice");
will print out "Bill and Alice"[/quote]
Link to comment
Share on other sites

I'm not sure what you guys are talking about, but in PHP -> is used to access things in classes and in PHP pointers follow this syntax
[code]
$foo="hello";
$bar=&$foo;

echo "{$foo} and {$bar}"; //will echo hello and hello
$foo="goodbye"

echo "{$foo} and {$bar}"; //will echo goodbye and goodbye
[/code]
Link to comment
Share on other sites

MCP, I'm still testing this out. I'm trying to figure out if "$a()" is a function, function-variable, a pointer or what. And what about the result from - $a("Bill");? I'm sure that I am barking up the right tree with you and KingPhilip's help. Thank.

fert, I agree with you regarding how PHP use pointers for variables. And this is the same way that C++ use variable pointers. However, C and C++ use arrays and function pointers somewhat differently, at lease this is what I think. I am still a novice when it come to PHP or C and C++.
Link to comment
Share on other sites

after looking in my handy PHP book i think i know what that code is doing
in the book it has this code
[code]
$result=$_POST['func']($_POST['text1']);
echo $result;
[/code]
The code is taking a function that the user inputed and passes the variable $_POST['text1'] to that function and displays the output
so the code that you have is doing the same thing except with imagecreatefrom
Link to comment
Share on other sites

Hmm.. not sure how to describe it. myNameFunc is the function. $a is a variable, and so I'd call $a() an expression (i.e. it's not one thing, but something that [i]evaluates[/i] to something else)

In this case:

$a("Alice") becomes myNameFunc("Alice") becomes "Bill and Alice"

Maybe this page entitled [url=http://www.php.net/manual/en/language.pseudo-types.php]Pseudo-Types used in this documentation[/url] will help clarify, see callback. The only thing is that they don't call the functions using [i]$a()[/i], but instead use [i]call_user_func($a);[/i]. But they do the same thing.

fert, be careful with that code! A malicious user will set $_POST['func'] to something really nasty, like "unlink" (which is PHP/C's way of saying delete file).
Link to comment
Share on other sites

fert, I am still testing and you have gave me something to think about. At the same time I am looking at the created variable or function "$x('y');" as some kind of place holder. However, I better think twice about my testing after seeing your code you posted above. Does your book tell you explicitly what the code is doing?

Thanks fert for the warnning and your input. I'll post whatever I find out if I thank it is helpful.

Hi there MCP.

$a("Alice") becomes myNameFunc("Alice") becomes "Bill and Alice" does seem to become one in the same. So it being call an expression might be the same as calling it a place holder(perhaps). I'm kind of clear on what it does and therefore I can make a decision if I should use it for the best results. I will check back periodically to see if anyone has any more info regarding this particular code.

Thank again KingPhilip, MCP and fert for all the help.



Link to comment
Share on other sites

Just an comment on fert's note, I'd advise against using that code straight up. Even though it's a POSTed form, I can just make my own form with "unlink" as a function (unlink == delete file in php), and it will delete stuff on your server. I strongly recommend you ensure in the php file that the function being called is allowed to be called! *Always* validate user input..
Link to comment
Share on other sites

Oooo bad idea!

Someone could make the form on their own machine and change the values then submit it or just put something like
[code]
javascript: document.form.<theformname>.func.value = "newfunction";
[/code]
In their address bar and it would change the value of the radio to a value of their choice.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.