March 16, 2015

Mafia Games Monday (MGM) – Magic OOP Methods

There are many words within a programming language that are considered reserved words, that is, they are predefined in the language that cannot be used anywhere else. So, for example, if you wanted to name a function as “int” in PHP, I.E:

function int($val) {
return $val;
}

Even with how simple that function is, it will not work! Why is that? Well, “int” is a reserved word in PHP, so when PHP attempts to run the code, it will treat “int” as the reserved word instead of a function name, which will cause the code to throw an error.

PHP Error

Why am I bringing this up? Well, in Object Oriented Programming (or OOP, which I have discussed in previous blog posts), there are also reserved methods, which PHP calls magic methods. What do these methods do? Well, it depends on the method, but they act like a reserved word: they cannot be used for other than the main purpose of the method. So, for example, remember the farmer class that I created in my Parent/Child classes blog post? Well, for those of you who do not remember the class itself, here it is:

class Farmer extends Person
{
public $numcows;
public $numtractors;
public $numland;

public function _construct($mf)
{
parent::_construct($mf);
$numcows = 0;
$numtractors = 0;
$numland = 0;
}
}

Now, looking at it, do you see the _construct() function? Why does it look that way?

Shrugs

Well, this is what PHP refers to as a magic method! As mentioned before, the _construct() function creates an instance of that particular class, which is its intended purpose. If you tried to create a _construct() function for any other reason than to create an instance of that class, then it will not work correctly for you and will throw an error.

If you are unsure of whether a PHP function is a magic method, look for the underscore ( _ ) in front of the function name. If it is there, that’s a good indicator that it is a magic method. If not, then this is not a magic method. Thank you PHP program creators for that easy identifiable trait!

Thank you!

If you are curious as to what all of the PHP magic methods are, then you can check them out here.

Do you like the idea of having magic methods? Why or why not?

That’s all for now, until next time…keep that tech gear ticking.

~Goliath7470