purpose of constructor in php [duplicate] - php

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Benefits of using a constructor?
hello coders. I am newbie to OOP in php. I am doing a project in objects and class. where
most of time I face a line
public function __construct(){
}
I can't understand this. Why its used and what is its value. Can some one tell me about it. I went to the php.net site but my doubt not cleared.

when using oop, a constructor gives basic initialization details for an object.
See:
http://en.wikipedia.org/wiki/Constructor_(object-oriented_programming)#PHP

The __construct allows arguments to be passed to an object on initalisation, without you would do something like this:
$myobj = new Object();
$myobj->setName('Barry');
But if you have this:
public function __construct($name='')
{
$this->name = $name;
}
You can just do:
$myobj = new Object('Barry');
Another possible use for the constructor (though not good practice):
public function __construct()
{
ob_start(); //Some random code that you may want to run as soon as object is initialised
}

It's a method within a class. When you construct an object from a class, this associated constructor is called. It has the "__" magic method prefix.

This method is automatically called when a class is instantiated.
There is also a __destruct() method, which as you might guess is automatically called when a class is destroyed.
Have a read here:
http://php.net/manual/en/language.oop5.decon.php

The value of the __construct is to initialize any newly created object in a method that's native to OO design.
So, rather than doing something like this:
$o = new MyObject();
$o->Initialize();
We can simply do this:
$o = new MyObject();
And within the MyObject class:
class MyObject
{
public function __contruct()
{
// initialization code here
}
}

Related

Calling a PHP method from an Object the proper way [duplicate]

This question already has answers here:
PHP: Static and non Static functions and Objects
(5 answers)
Closed 8 years ago.
I am still learning OOP PHP and I keep swapping and changing between the following way of calling methods within an object
$obj = new Model();
$obj->method($param);
against
Model::method($params);
I understand the difference when I within the method as I can use $this in the first example, and I have to use self:: in the second.
Which is the correct way and what are the reasons of using each way
The reason I ask is I cannot find a suitable search term to research. I am currently reading a book on OOP and it will probably tell at some point, but would be nice to know now.
Foo::bar() calls the static class method, while $foo->bar() calls the instance method on an object. These are two completely different things. You do not need an object instance to call Foo::bar(), and in fact you do not have access to instance data when doing so. Foo::bar() is essentially nothing else but a regular function call like bar(), except that the function is attached to a class.
Instance methods act on a specific object instance:
class User {
protected $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public static function hi() {
// no access to $this->name here, since static
// methods are not bound to specific instances
echo 'Hi';
}
}
$dave = new User('Dave');
$mary = new User('Mary');
echo $dave->getName(); // Dave
echo $mary->getName(); // Mary
User::hi(); // Hi
Unless you understand this, you know nothing about OOP.
First example is a non-static call to the method, second a static call.
The first is better if you want to access private variables of your Model, second is better if you use the method like a normal function.
In general you should declare methods of the first type as static (public static function method(){}).
First case is invocation of method on class instance, second case is call of static method.
See http://php.net/manual/en/language.oop5.static.php
There is no "proper" way because both call types serve different purposes.
The first call type is the standard way of handling objects: You initialize a concrete instance of a class. This instance can have its own internal values and each instance can use these values to create a different result when you call the method with the same parameter.
The second call type is called static and operates directly on the class, there is no instance (hence no $this). There are some use cases for it, see this answer for Java, it's the same for PHP.

Diffrences of $this:: and $this-> in php [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: self vs. $this
I've found that I can call class methods by $this:: prefix. example:
class class1 {
public function foo()
{
echo "1";
}
public function bar()
{
$this::foo();
//in this example it acts like $this->foo() and displays "2"
//using self::foo() displays "1"
}
}
class class2 {
public function foo()
{
echo "2";
}
public function bar()
{
class1::bar();
}
}
$obj = new class2();
$obj->bar(); // displays "2"
class1::bar(); // Fatal error
I want to know whats the diffrence of calling method with $this-> and $this:: prefixes.
ps:
There is a page about diffrence of $this->foo() and self::foo() in this link:
When to use self over $this?
The answer that you linked tells you exactly what you're looking for ;).
Basically, there are two concepts that some people have a tough time differentiating in programming languages: objects and classes.
A class is abstract. It defines a structure of an object. The properties and methods that an object would contain, if an object were built from that class. Creating an object is what you do when you call new class1(). This is instructing PHP to create a new object with all of the properties and methods on the class1 class.
The important thing to note about creating an object is that it also has its own scope. This is really where $this vs static:: (note: do not use self:: or $this::, please use static:: (more on this later)) come in to play. Using $this is instructing PHP to access the properties and methods of your current object. Using static:: is instructing PHP to access the properties and methods of the base class that your object is constructed from.
Here's an example:
class MyClass {
public $greeting;
public static $name;
public greet() {
print $this->greeting . " " . static::$name;
}
}
$instance1 = new MyClass();
$instance1->greeting = 'hello';
$instance2 = new MyClass();
$instance2->greeting = 'hi';
MyClass::$name = 'Mahoor13';
$instance1->greet();
$instance2->greet();
I didn't test the above, but you should get:
hello Mahoor13
hi Mahoor13
That should give to a general idea of the difference between setting a class property and setting an instance property. Let me know if you need additional help.
Edit
$this:: appears to just be a side effect of the way that PHP handles scopes. I would not consider it valid, and I wouldn't use it. It doesn't appear to be supported in any way.
the $this-> is called from instance , so you have to have an instance of the object to use this call.
but $this:: is a static method inside the class you can call it without instance so you do not need to alloc an instance of the class to call it like
myclass::doFoo();
public static function doFoo(){ .... }
and the do function should be static function to call it like this or the php will give error in the newer versions

Access a class field from static method

For example, I have a class
class MyClass
{
public $something = 'base';
public function __construct()
{
$something = 'construct';
}
public function __destruct()
{
$something = 'destruct';
}
public static doSomething()
{
$return = new MyClass;
echo $return->something;
}
}
So, my question is this... Will running the static method without instantiating the object run the constructor? If I had, for example, database connection information in the constructor, could I run a static method that returns a query withing explicitly instantiating the class?
Thanks in advance
Yes the construction will be called in your example. Since you already have the code, I guess it would be easy to test.
If you execute MyClass::doSomething(), it will create object of MyClass and, of course, its constructor will be called. Why not to run it and see the result?
I'm lacking PHP knowledge, but compared to other OO languages it will of course run the constructor, because you tell the static method to create a new instance of MyClass.
The same would apply if you called a new SomeOtherType. The code itself doesn't care if it's inside a static/public/private method, as long as new is there, the constructor is invoked.
I did not ask the question correctly, but the answer is that as long as the object is instantiated, even within a static method, the constructor will run. The output would be whatever is in the constructor as the deconstructor does not fire until after the last call to the class.
Sorry for the confusion in the question.

Use an instance of an object throughout the site with PHP

How will I use an instance of an object that is initially loaded throughout the whole site?
I want $myinstance to be used everywhere.
$myinstance = new TestClass();
Thanks!
What you are looking for is called the singleton pattern.
If you are deeply into OOP architecture, and want to do things like Unit Testing in the future: Singletons are regarded as an imperfect approach and not "pure" in the sense of OOP. I asked a question on the issue once, and got pretty good results with other, better patterns. A lot of good reading.
If you just want to get started with something, and need your DB class available everywhere, just use a Singleton.
You just need to declare your variable in global scope (for example, in the begginning of your whole code), and when you want to use it inside a function, use the "global" statement. See http://php.net/global.
I'm not 100% sure I got what you want to do... but I'll try to answer anyway.
I think you can save it to a session variable, using the serialize/unserialize functions to save/retrieve your class instance. Probably you'd code TestClass as a singleton, but that really depends on what you're trying to do.
For instance:
if (!isset($_SESSION["my_class_session_var"])) // The user is visiting for the 1st time
{
$test = new TestClass();
// Do whatever you need to initialise $test...
$_SESSION["my_class_session_var"] = serialize($test);
}
else // Session variable already set. Retrieve it
{
$test = unserialize($_SESSION['my_class_session_var']);
}
There is a design pattern called Singleton. In short:
Change __construct and __clone to private, so calling new TestClass() will end up with Error!
Now make a class that will create new instance of your object or return existing one...
Example:
abstract class Singleton
{
final private function __construct()
{
if(isset(static::$instance)) {
throw new Exception(get_called_class()." already exists.");
}
}
final private function __clone()
{
throw new Exception(get_called_class()." cannot be cloned.");
}
final public static function instance()
{
return isset(static::$instance) ? static::$instance : static::$instance = new static;
}
}
Then try to extend this class and define static $instance variable
class TestClass extends Singleton
{
static protected $instance;
// ...
}
Now try this:
echo get_class($myinstance = TestClass::instance();
echo get_class($mysecondinstance = TestClass::instance());
Done

Calling PHP Class

Is there any way to call a php class (eg. $var = new className) and have var store the value returned by the className function?
Or, is there a way to call a class and not have it execute the function with the same name?
The function of the same name as the class was they way 'constructors' in php 4 worked.
This function is called automatically when a new object instance is created.
In php 5, a new magic function __construct() is used instead.
If your using php5 and don't include a '__construct' method, php will search for an old-style constructor method.
http://www.php.net/manual/en/language.oop5.decon.php
So if you are using php5, add a '__construct' method to your class, and php will quit executing your 'method of the same name as the class' when a new object is constructed.
It is possible in PHP5 using magical method __toString(); to return a value from the class instance/object.
simply
class MyClass{
function __construct(){
// constructor
}
function __toString(){
// to String
return 5;
}
}
$inst = new MyClass();
echo $inst; // echos 5
Constructors don't return value (in fact you can't do that). If you want to get a value from the instance of the class, use the __toString() magical method.
Constructors don't return values, they are used to instantiate the new object you are creating. $var will always contain a reference to the new object using the code you provided.
To be honest, from your question, it sounds like you don't understand the intention of classes.
$var = new classname will always return an instance of classname. You can't have it return something else.
Read this...
http://www.php.net/manual/en/language.oop5.php

Categories