This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
PHP: Static and non Static functions and Objects
Why would I use the static key word in php? Is it only to create "good" code or does it have some advantages as well?
function useThisAsStatic(){}
static function useThisAsStatic(){}
public static function useThisAsStatic(){}
public function useThisAsStatic(){}
To clarify the question; all above methods can be used by calling
Object::useThisAsStatic();
And thus suggests that there is no difference in declaring a method to be static.
Is it only to create "good" code
Actually it's to create bad code.
Read why
And this article is more specified about static (thanks to Gordon)
Static functions mean you can call them without instantiating the class (creating the object) first.
Useful in certain situations, but static functions cannot make use of the local members of the class outside of that function.
static means belonging to the Class. You can call a static method or field. Without creating instance of the class.
class NewClass {
public $public_var = "I'm public property!";
public static $static_var = "I'm static property!";
public function public_method()
{
return "I'm public method!";
}
public static function static_method()
{
return "I'm static method!";
}
}
Now you can call NewClass::$static_var and NewClass::static_method() without creating NewClass instance.
While to call public_var and public_method you should create new instance of class:
$c = new NewClass();
echo $c->public_var;
echo $c->public_method();
Related
This question already has answers here:
PHPUnit - Use $this or self for static methods?
(3 answers)
When should I use 'self' over '$this'?
(23 answers)
Closed 3 years ago.
I was messing around and discovered that you could actually call static methods with $this->method()
And it got me a bit confused and curious about the differences between the 3 ways (that I know of) to call static methods
$this->method();
static::method();
self::method();
Now, I think I understand the difference between the latter two, but what about the first one?
It is important to understand the behavior of static properties in the context of class inheritance:
Static properties defined in both parent and child classes will hold DISTINCT values for each class. Proper use of self:: vs. static:: are crucial inside of child methods to reference the intended static property.
Static properties defined ONLY in the parent class will share a COMMON value.
declare(strict_types=1);
class staticparent {
static $parent_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromparent';
static::$both_distinct = 'fromparent';
}
}
class staticchild extends staticparent {
static $child_only;
static $both_distinct;
function __construct() {
static::$parent_only = 'fromchild';
static::$both_distinct = 'fromchild';
static::$child_only = 'fromchild';
}
}
$a = new staticparent;
$a = new staticchild;
More on https://www.php.net/manual/en/language.oop5.static.php
self using for static method and variable in class
$this using for non static method and variable
static generally using call child class of static methods or variable
For example late static
For example late static binding
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
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
}
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
PHP: self vs this
Hello,
Could you help me understanding the meaning of the PHP variable name $this?
Thank you for your help.
$this refers to the class you are in.
For example
Class Car {
function test() {
return "Test function called";
}
function another_test() {
echo $this->test(); // This will echo "Test function called";
}
}
Hope this helps.
You might want to have a look at the answers in In PHP5, what is the difference between using self and $this? When is each appropriate?
Basically, $this refers to the current object.
$this is a protected variable that's used within a object, $this allows you to access a class file internally.
Example
Class Xela
{
var age; //Point 1
public function __construct($age)
{
$this->setAge($age); //setAge is called by $this internally so the private method will be run
}
private function setAge($age)
{
$this->age = $age; //$this->age is the variable set at point 1
}
}
Its basically a variable scope issue, $this is only allowed within a object that has been initiated and refers to that object and its parents only, you can run private methods and set private variables where as out side the scope you cannot.
also the self keyword is very similar apart from it refers to static methods within class, static basically means that you cant use $this as its not an object yet, you must use self::setAge(); and if that setAge method is declared static then you cannot call it from an instant of that object / object
Some links for you to get started:
http://php.net/manual/en/language.variables.scope.php
http://php.net/manual/en/language.oop5.static.php
How to explain 'this' keyword in a best and simple way?
When to use self over $this?
I'm thinking about putting every class into a separate file and doing the static initialization outside of the class definition.
The problem with this is the fact that the initialization will happen before the said class is actually needed (it will happen when the file which contains the class is included for the first time). It's a problem, because it may happen that the class won't be used at all, hence the initialization is unnecessary. And I think the practice of including the used files not in the beginning of your code is simply a dirty technique.
If anybody has a viable solution to this problem, I would greatly appreciate it.
Take a look at code like this. It uses a singleton instance of the database yet you can still create instances of the class:
class DB
{
private static $_db;
public static function pdo()
{
if (is_null(self::$_db))
{
self::$_db=new PDO('pgsql:host=localhost;
port=5432;
dbname=testdb;
user=postgres;
password=abc123');
self::$_db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return self::$_db;
}
public static function factory()
{
return new self;
}
private function __construct() {}
When you want an instance of the DB, you do DB::factory(). DB uses self::pdo() to return the singleton to access the database.
The singleton answer has a problem here... if you use the static methods before an instance of the class is created... then the static initializer has not run... so you might say that one can run the initializer in every static method... that is true but what about just getting and setting static variables... I suppose one could also use __get and __set magic functions for this... there is just a problem with the language in that it does not support static intialization... here is the way it can be done...
in file Hi.php:
class Hi{
public static $v = "0";
}
Hi::$v= "2";
// end of Hi.php file
simple use a .php file per class... and do the static initialization outside of the
class definition...
You might look up for __autoload when a class is not found it is called and supposed to include the file contains that class. You can put static initializers in that function.
Use singleton pattern instead of static calls:
<?php
class Foo {
protected static $_instance;
/**
* #return Foo
*/
public static function getInstance() {
return (null === self::$_instance)?
self::$_instance :
self::$_instance = new Foo();
}
protected function __construct() {
// initialize here
}
}
This is the way I do this. The only cost is testing the $doneinit static member each time you construct.
class Foo {
private static $doneinit=false;
private static init() {
// do static initialisation here
self::$doneinit=true;
}
public function __construct() {
if (!self::$doneinit) self::init();
// go on to do the rest of construction
}
}
Simple, and it keeps everything within the class.