This question already has answers here:
When should I use 'self' over '$this'?
(23 answers)
Closed 9 years ago.
I'm reading a book of php and found this code:
class Employee {
static public $NextID = 1;
public $ID;
public function _ _construct( ) {
$this->ID = self::$NextID++;
}
public function NextID( ) {
return self::$NextID;
}
}
why here is used self::$NextID++; can I use like this:
$this-ID = $this->$NextID++;
Because in php you have to reference static functions with self.
There was also an explanation on stackoverflow already: see here
When a class is called statically ie. ClassName::someMethod(), there is no "instance" of the class.
Since $this refers to the instance of the class, $this will not exist when your class is used statically. (so $this will only be available when you created an object of your class by using $var = new ClassName())
self refers to the class (not the object) so in static classes you can use self::.. to refer to properties or methods within the class.
Related
This question already has answers here:
What is the difference between self::$bar and static::$bar in PHP?
(5 answers)
Closed 3 years ago.
I'm wanting to create an class inheriting (extending) another PHP class with a protected const that I want to override in my extending class.
I created a parent class (A for the example) and an inheriting class (B for the example). class A has a protected const (named CST) defined. class B overrides this const as well.
When calling a method class B inherited from A that displays self::CST, the printed value is the CST value from A, not the const CST overrided in B.
I observe the same behavior with a static property named $var.
It seems that self used in methods is always refering to the defining class (A in my example) and not the class used for calling the static method.
class A
{
protected static $var = 1;
protected const CST = 1;
public static function printVar()
{
print self::$var . "\n";
}
public static function printCST()
{
print self::CST . "\n";
}
}
class B extends A
{
protected static $var = 2;
protected const CST =2;
}
A::printVar();
A::printCST();
B::printVar();
B::printCST();
Is there a way to permit my static method printCST() to display 2 when called with B::printCST() without rewriting the method in class B and to benefit code reusability of OOP?
Dharman suggested to use static::CST instead of self::CST.
This was the solution to my problem.
This question already has answers here:
Overriding class constants vs properties
(2 answers)
Inheritance of static members in PHP
(3 answers)
Closed 4 years ago.
<?php
class A{
static $var;
function test(){
var_dump(self::$var);
}
}
class B extends A{
static $var = 'something';
}
$b = new B();
$b->test();
?>
why does this print out null and how do I fix this? It works if I do not set $var as static but i need it to be accesible without creating an instance.
$b->test(); prints null because it is null. When you do this:
class B extends A{
static $var = 'something';
}
you're not actually doing anything to the $var property in your A class. The property is defined with the static keyword, and per the docs, "A property declared as static cannot be accessed with an instantiated class object (though a static method can)." Thus you cannot inherit it (or subsequently set it) from your B class.
If you want the test() method to output anything meaningful, you need to set it statically, such as:
A::$var = "something";
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how do i access static member of a class?
I have this class. In its createNew function I refer to $reftbArr = tc_group::$tblFields;.
I have many classes similar to this class a couple of times. They have the same methods and variables but of course the class name is different.
How is the best way in the function createNew to access tc_group::$tblFields; but not have the hardcoded class name?
<?php
class tc_group {
public $id;
public $password;
private static $tableName = "tc_group";
public static $tblFields = array(
':id' => array('value' => '','required' => 0),
':password' => array('value' => '','required' => 0)
);
public static function createNew($link , $tblfields){
$reftbArr = tc_group::$tblFields;
}
}
?>
You can use self for example: self::$variable
You can use static for example: static::$variable
The difference is that self will access the current class it is used in (ignoring inheritance), static will obey inheritance.
Extended Answer
I have this same class a couple of times. they have the same methods and vars but of course the class name is different.
That sounds like it needs refactoring. In which case create an "abstract class" which defines all the properties and methods defined by the other classes and remove them from the other classes (as they are now in the abstract class). Then extend the abstract class to create the separate classes as needed that contain ONLY WHAT CHANGES in them.
$tableFields = self::$tblFields;
print_r($tableFields);
You would use the static keyword self.
public static function createNew($link , $tblfields){
$reftbArr = self::$tblFields;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Reference - What does this symbol mean in PHP?
So I've been reading through the book PHP Solutions, Dynamic Web Design Made Easy by David Powers. I read through the short section on Object Oriented PHP, and I am having a hard time grasping the idea of the -> operator. Can anyone try to give me a solid explanation on the -> operator in OOP PHP?
Example:
$westcost = new DateTimeZone('America/Los_Angeles');
$now->setTimezone($westcoast);
Also,a more general example:
$someObject->propertyName
The -> operator in PHP refers to either a function or a variable inside a class.
<?php
class Example {
public $variableInClass = "stringContent";
public function functionInClass() {
return "functionReturn";
}
}
$example = new Example();
var_dump($example->variableInClass); //stringContent
var_dump($example->functionInClass()); //functionReturn
?>
Do note that if we're talking about static classes (different purpose), you use :: instead:
<?php
class Example {
public static $variableInClass = "stringContent";
public static function functionInClass() {
return "functionReturn";
}
}
var_dump($example::$variableInClass); //stringContent
var_dump($example::functionInClass()); //functionReturn
?>
$someObject->propertyName can be read as:
return value stored in propertyName from object $someObject
$someObject->methodName() can be read as:
execute methodName from object $someObject
Classes and objects 101:
A class is defined as such:
class MyClass {
public $value1;
public function getValue() {
return $this->value;
}
}
We now defined a class with a single property, and a single function. To use these, we need to create an 'instance' of this object:
$myObject = new MyClass();
To use the property or function, we use the -> operator:
echo $myObject->value1;
echo $myObject->getValue();
Put a little bit more abstractly.. the function getValue is defined in this object. By using the -> operator on an instance of our class, what PHP does is effectively just call the function, just like any other function.. but before it gets called $this is assigned to the current object.
Hope this helps, if not.. I would simply recommend reading about OOP basics.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calling closure assigned to object property directly
Why this is not possible in PHP? I want to be able to create a function on the fly for a particular object.
$a = 'a';
$tokenMapper->tokenJoinHistories = function($a) {
echo $a;
};
$tokenMapper->tokenJoinHistories($a);
PHP tries to match an instance method called "tokenJoinHistories" that is not defined in the original class
You have to do instead
$anon_func = $tokenMapper->tokenJoinHistories;
$anon_func($a);
Read the documentation here especially the comment part.
With $obj->foo() you call methods, but you want to call a property as a function/method. This just confuses the parser, because he didn't find a method with the name foo(), but he cannot expect any property to be something callable.
call_user_func($tokenMapper->tokenJoinHistories, $a);
Or you extend your mapper like
class Bar {
public function __call ($name, $args) {
if (isset($this->$name) && is_callable($this->$name)) {
return call_user_func_array($this->$name, $args);
} else {
throw new Exception("Undefined method '$name'");
}
}
}
(There are probably some issues within this quickly written example)