top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

In PHP, what are magic methods and how are they used?

+2 votes
86 views
In PHP, what are magic methods and how are they used?
posted Jun 18, 2015 by Vrije Mani Upadhyay

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

PHP functions that start with a double underscore – a “__” – are called magic functions (and/or methods) in PHP. They are functions that are always defined inside classes, and are not stand-alone (outside of classes) functions.

The magic functions available in PHP are:

__construct(), 
__destruct(), 
__call(), 
__callStatic(), 
__get(), 
__set(), 
__isset(),
 __unset(), 
__sleep(), 
__wakeup(), 
__toString(), 
__invoke(), 
__set_state(), 
__clone(),
and 
__autoload().
answer Jun 22, 2015 by Manikandan J
Similar Questions
+2 votes

I have been looking at my copy of the php manual, at magic constants and have a question about two of them.

1: __line__ : I presume that this would be irrelevant if a script file was compressed by removing all the superfluous white space, including line breaks and tabs? (Although since php is not exposed to the client unless the developer uses highlight_file or highlight_string, compressing it this way is not too useful)

2: __trait__: This is the first time I have run into this term in a programming context. What does it mean? In the manual there is an associative reference to namespace. Perhaps I should read up on namespaces relative to php. The only other context I am aware of the term is in XML This is a bit confusing because I have seen the term used referring to object/property relationships, such as in javascript.

Specifically, you can create an object through the use of a constructor function

function SomeJSObj()
 {
   this.introduce = function(a)
   {
    alert('Hi, I am '+a)
   }
 }

var guy = new SomeJSObj()

guy.introduce('Max') // -> alert dialog -> "Hi, I am Max"

So the function/property 'introduce' is namespaced by the object guy.

So, how is it different than a member function or variable of a class that can only be accessed via reference to an object instance?

Then, finally, how does the term inferred by __trait__ relate?

+1 vote

I am working on an OOP project, and cannot decide which way to follow when I have to write a simple function.

For example, I want to write a function which generates a random string. In an OOP environtment, it is a matter of course to create a static class and a static method for that. But why? Isn't it more elegant, if I implement such a simple thing as a plain function? Not to mention that a function is more efficient than a class method.

So, in object-oriented programming, what is the best practice to implement such a simple function?

...