What Is the Function _Construct Used For

What is the function __construct used for?

__construct was introduced in PHP5 and it is the right way to define your, well, constructors (in PHP4 you used the name of the class for a constructor).
You are not required to define a constructor in your class, but if you wish to pass any parameters on object construction then you need one.

An example could go like this:

class Database {
protected $userName;
protected $password;
protected $dbName;

public function __construct ( $UserName, $Password, $DbName ) {
$this->userName = $UserName;
$this->password = $Password;
$this->dbName = $DbName;
}
}

// and you would use this as:
$db = new Database ( 'user_name', 'password', 'database_name' );

Everything else is explained in the PHP manual: click here

What is the function __construct in PHP used for?

The __construct method is usually the method called in a class when an instance of that class is created (called an object). The method is called the constructor because it constructs the object, but that doesn't mean you must use the method to do so.

The point of the method is to set the variables of the object to their inital values, which may be a primitive type such as an integer, or perhaps an instance of another class. If the variables are to be something other than a default value, the __construct method can accept arguments to set the values of the variables.

You don't have to set the variables using the constructor method, nor is it the only thing you can do. You could, for example, print a success message or call another method, either in that class or elsewhere. So your two examples are both valid. The first is how you would expect the constructor to be used, but the second is still vaild. Like I said, __construct is the method that is called on creation of the object, which doesn't mean you have to use it for the intended purpose.

In PHP, it is not required to have a constructor method in a class, but in many other object orientated programming languages, such as Java, if a constructor is not present then it will produce an error at compile time. This is because PHP is what is know as a weakly typed language, which has many pros and cons which you can research further.

Because __construct is one of the magic methods specifically used in a PHP class, it cannot be converted into procedural code. To call the method with arguments, when you assign a class in your code you should give your arguments in the creation statement, like this;

$object = new MyClass($arg1,$arg2);

You cannot call the constructor from outside the class, other than when creating a new object. The only exception to this is a child class (ie, a class that extends another class) can call the constructor of its parent using parent::__construct();.

Why does Magento have _construct and __construct methods?

Best answer I can find: http://www.magentocommerce.com/boards/viewthread/76027/#t282659

Basically, the root-level class (from which all other classes inherit) implements __construct, which PHP calls automatically whenever a class is constructed. Right now, this root-level class simply calls _construct, which contains the actual code.

Say you have this set-up:

class BaseClass {
function __construct() {
print "In BaseClass constructor\n";
doSomethingReallyImportant();
}
}

class SubClass extends BaseClass {
function __construct() {
print "In SubClass constructor\n";
}
}

$obj = new BaseClass();
//"In BaseClass constructor"
//something really important happens

$obj = new SubClass();
//"In SubClass constructor"
//important thing DOESN'T happen

PHP doesn't automatically call the parent class constructors, so doSomethingReallyImportant never gets called. You could require that subclass constructors call parent::__construct(), but that's easy to forget. So Magento has subclasses override _construct:

class BaseClass {
function __construct() {
doSomethingReallyImportant();
_construct();
}
function _construct() {
print "In BaseClass constructor\n";
}
}

class SubClass extends BaseClass {
function _construct() {
print "In SubClass constructor\n";
}
}

$obj = new BaseClass();
//something really important happens
//"In BaseClass constructor"

$obj = new SubClass();
//something really important happens
//"In SubClass constructor"

PHP doesn't detect a constructor in SubClass, so it calls BaseClass's constructor. This allows BaseClass to doSomethingReallyImportant before calling SubClass's overridden _construct.

What's difference between __construct and function with same name as class has?

The method named is the PHP4 way of doing a constructor.

For backwards compatibility, if PHP 5 cannot find a __construct() function for a given class, it will search for the old-style constructor function, by the name of the class. Effectively, it means that the only case that would have compatibility issues is if the class had a method named __construct() which was used for different semantics.

As of PHP 5.3.3, methods with the same name as the last element of a namespaced class name will no longer be treated as constructor. This change doesn't affect non-namespaced classes.

http://www.php.net/manual/en/language.oop5.decon.php

PHP - used __construct() to check if there is a session

I suggest you to create your own library file in library folder
Here is the class file

class Authenticate {
var $table;
public function __construct()
{
$this->ci =& get_instance();

}
public function is_logged_in()
{
$sessionid = $this->ci->session->userdata('moderId');
if($sessionid)
{
return isset($sessionid);
}
else if(!$sessionid) {
redirect(base_url() . 'moderator');
}
}
}

And in your controller,use this function.if you put this function in the constructor of the controller,then it wil be available to all methods
Controller

class B2bcategory extends CI_Controller {

function __construct() {
parent::__construct();

$this->load->model('moderator/b2bcategory_model');

$this->authenticate->is_logged_in();
}
}

Access function from public construct in php

The error outputted when I ran your code was;

'Object of class test could not be converted to string'

There are 2 ways you can solve this problem, you can use either;

  1. Instead of the line echo($j); change it to echo($j->var0);

Now instead of trying to print the object you are now printing the public variable from the object which was set in the constructor.


  1. Add a __toString() method to your object, and use this to output the var0 field.

    class test {

    public $var0 = null;

    public function __construct() {

    $this->var0 = Tfunction('lol');

    }

    public function __toString(){

    return $this->var0;

    }

    }

    function Tfunction ($String) {

    $S = ($String . ' !');

    return $S;

    }

    $j = new test();

    echo($j);

Now when you try to print the object with echo($j); it will use the __toString() you assigned to output your variable.

Both of theses fixes mean that 'lol!' was outputted to my browser window, as was originally expected.

When do/should I use __construct(), __get(), __set(), and __call() in PHP?

This page will probably be useful. (Note that what you say is incorrect - __set() takes as a parameter both the name of the variable and the value. __get() just takes the name of the variable).

__get() and __set() are useful in library functions where you want to provide generic access to variables. For example in an ActiveRecord class, you might want people to be able to access database fields as object properties. For example, in Kohana PHP framework you might use:

$user = ORM::factory('user', 1);
$email = $user->email_address;

This is accomplished by using __get() and __set().

Something similar can be accomplished when using __call(), i.e. you can detect when someone is calling getProperty() and setProperty() and handle accordingly.

use function __construct() for static functions?

You have to create a new instance of class user inside say_hi() method. When you create the instance inside say_hi() method, it will call the constructor method and subsequently define the constant HI.

So your code should be like this:

class user{
function __construct(){
define('HI', 'hello');
}

static function say_hi(){
new user();
echo HI ;
}
}

user::say_hi();

Output:

hello 


Related Topics



Leave a reply



Submit