Why can functions be executed using variables?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
iliekphp
Forum Newbie
Posts: 4
Joined: Tue Sep 28, 2010 9:51 pm

Why can functions be executed using variables?

Post by iliekphp »

I'm aware that this works, but I don't quite understand how. I'm kind of new to programming in general so forgive me if this is some basic concept.

So for example:


<?php

$dbc = mysqli_connect('localhost', 'root', '', ''databasename')
or die("Can't connect");

$query = "INSERT INTO tablename (value, value2, value3)
VALUES ('value', 'valuee', 'valueee');";

$result = mysqli_query($dbc, $query)
or die("Cannot query database");

mysqli_close($dbc);

?>
why does simply declaring the mysqli_query function in a variable make it work? Why does this function get parsed just for being in a variable? Also does this work on all functions? Thanks.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Why can functions be executed using variables?

Post by John Cartwright »

You do not need to capture the return value of the function.

Code: Select all

mysqli_query($dbc, $query)or die("Cannot query database");
Would have worked just the same.

In your case, you it is usually a good practice to check the return values of query operations, to 1) make sure they ran correctly 2) furthur processes using that query, such as with mysqli_num_rows requires the resource returned from the query.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Why can functions be executed using variables?

Post by requinix »

Preeetty sure you got your terminology wrong. There are no variable functions in that code. No "declaring the mysqli_query function in a variable" or "function get parsed" in there. Just regular function calls.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Why can functions be executed using variables?

Post by califdon »

Saying the same thing in different words, this line of code:

Code: Select all

$result = mysqli_query($dbc, $query) or die("Cannot query database");
is simply assigning the value that is returned by the mysqli_query() function to the variable $result, or if the function returns the value False, it calls the die() function.
Post Reply