The difference between "public" and "public static"? - php

What does static mean?
I know public means that it can be accessed from outside the class, and private only from inside the class…

Static means that it can be accessed without instantiating a class. This is good for constants.
Static methods need to have no effect on the state of the object. They can have local variables in addition to the parameters.

public: Public declared items can be accessed everywhere.
protected: Protected limits access to inherited and parent
classes (and to the class that defines the item).
private: Private limits visibility only to the class that defines
the item.
static: A static variable exists only in a local function scope,
but it does not lose its value when program execution leaves this scope.
final: Final keywords prevents child classes from overriding a
method by prefixing the definition with final. If the class itself is
being defined final then it cannot be extended.
Beside of PHP:
transient: A transient variable is a variable that may not
be serialized.
volatile: A variable that might be concurrently modified by multiple
threads should be declared volatile. Variables declared to be volatile
won't be optimized by the compiler because their value can change at
anytime.

From http://php.net/manual/en/language.oop5.static.php
Declaring class properties or methods
as static makes them accessible
without needing an instantiation of
the class. A property declared as
static can not be accessed with an
instantiated class object (though a
static method can).

An example: when use the static keyword, we cannot use $this
class Foo {
private $foo='private';
private function priv_func() {
echo 'priv_method';
}
public static function get() {
echo $this->foo;
$this->priv_func();
}
}
$obj = new Foo();
$obj->get();
Fatal error: Using $this when not in object context in (…)

Example:
public class Methods_Test1
{
public static void Display(String Name)
{
System.out.println("Hello There " + Name);
System.out.println("I am from Display method");
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter name");
String name = sc.next();
Obj.Display(name);
}
The public static void Display(String name) method accessible as static method within its own class which can be accessed without creating object of the class where as the same method behaves as public for the outside classes which can be accessed by creating object.

Related

Late static bindings | static:: usage in a non-static context

Php manual for the late static bindings states, in the example of static usage in non-static context, that foo() will be copied to B? Is method inheritance copying with scope of the original function being maintained?
<?php
class A {
private function foo() {
echo "success!\n";
}
public function test() {
$this->foo();
static::foo();
}
}
class B extends A {
/* foo() will be copied to B, hence its scope will still be A and
* the call be successful */
}
class C extends A {
private function foo() {
/* original method is replaced; the scope of the new one is C */
}
}
$b = new B();
$b->test();
$c = new C();
$c->test(); //fails
As far as I can say, this is a problem of scope. When a child class does not override a parent's class method and you call said method via the child class, you will be in the parent class's scope and have access to private methods of the parent class.
If you implement a test() method in the child class, you will have that scope when you call it and will not be able to access private methods of the parent class.
I would say that 'copy' is not a fitting term for what's happening because the parent methods are not copied, they are just available in the child class, given the right scope. That is, they don't take the scope of the child class, but keep their own. They are only accessible in the child class if set to protected (or public) or if you call private methods with the parent's scope (as described in your example).
More information from your linke here: Strange behavior when overriding private methods
The official documentation does not explain it explicitly, but I could find this:
Private methods of a parent class are not accessible to a child class. As a result, child classes may reimplement a private method themselves without regard for normal inheritance rules.

Can we access properties without $this?

Is there any way we can create another property in class (i.e. $myVar), which wouldn't need to prepend $this-> and can be called directly (like $this is used), i.e.:
...
public function hello()
{
echo $myVar; //instead of $this->myVar
}
Please note, I clearly emphasize that "creating local variables inside method" is out of the question.
You cannot access property without specifying its scope. If you refer to it by its name, you are referring to a local variable.
To access properties you need to use -> (Object Operator). Static properties are accessed using the :: (Double Colon; also called Paamayim Nekudotayim).
If you would like to access a property inside of a class method you would use either of these two operators in connection with scope keyword. To access the scope of the current object within one of its methods, you can use the pseudo-variable $this. For static properties, you would use self or static to refer to the current class. To access the parent class, you would use parent. Combining all of it:
class B{
static protected $s1;
}
class A extends B {
protected $v1 = 'foo';
static protected $s1;
static private $s2;
public function __construct()
{
print_r($this->v1);
print_r(parent::$s1);
print_r(self::$s1);
print_r(static::$s2);
}
}
For more information, see: PHP: self:: vs parent:: with extends
However, nothing stops you from creating new local variables inside class methods.
class C {
private $var1 = 'bar';
public function func() {
$var1 = 'foo';
print_r($var1); // This is 'foo' not 'bar'
}
}
It all comes down to the scope in which the variable resides. You have different operators and keywords for each scope resolution, but you can create local variables as you would anywhere else in the code.

PHP - when to use private static properties in the class

I am learning php and there are still alot of unclear areas for me in the language. I wonder when and why would we use private static properties inside the class. From what I understood private properties may only be accessed by the class where it was defined. So, the private part is clear, but the static is still unclear. In the docs it says:
Declaring class properties or methods as static makes them accessible
without needing an instantiation of the class. A property declared as
static cannot be accessed with an instantiated class object (though a
static method can).
Does that mean that I can access static properties without instantiation of the class. So, for example:
class Foo{
static $bar;
public function __construct($bar){
$this->bar = $bar;
}
So, I can access the $bar property of the class like so?
Foo::$bar
But, if I do this, it wouldn't work?
$foo = new Foo();
$foo::$bar
And, then if do make a property private static for which reason would we do that, since I thought we make them static in order to access them outside of their class and making them private would make that impossible. I would be very grateful if someone could clear this up to me.
When you declare a normal property, there is a different value of that property for every instance you create of that class (each object you create with new Foo). For a static property, there is one copy of that variable for the whole class.
This is separate from the visibility of that variable - a public static property exists once per class, and can be accessed from everywhere; a private static property exists once per class, but can only be accessed from inside that class's definition.
As a simple example, you could have a counter that gave each instance of the class a unique number. You don't need code outside the class to see or change this counter, so you mark it private, but it needs to be shared amongst all instances, so you mark it static.
class Foo {
// Static counter; shared with every instance
private static $nextID=0;
// Normal instance property: each instance will have its own value
private $myID;
public function __construct() {
// Set the ID for this instance to the next ID
$this->myID = self::$nextID;
// Increment the shared counter
self::$nextID++;
}
}
Static context within a PHP class (but outside of a function) is context which exists statically, that is without the need for a backing instance of an object.
Example:
class A {
public $a = 1;
public static $b = 2;
public function instanceFunction() {
A::$a; //Wrong way
$this->a //Right way
A::$b; //Works
self::$b; // Also works
static::$b; // Also also works
}
public static function staticFunction() {
A::$a; //Does not work
$this->a //Error $this within static context
A::$b; //Works
self::$b; // Also works
static::$b; // Also also works
}
}
A::$a; // Error $a is not static so it needs an instance of an object
A::$b; // Works
$Aobject=new A();
$Aobject->a; //Works
$Aobject->b // Does not work
Using self means "refer to the class I've written this in" e.g. in this case it's always A. Using static means "refer to the class I've called this from" which applies if static inheritance is involved which PHP does manage to pull off.

Using $this when not in object context php

I just started learning OOPS in php. I wrote a simple program for implementing inheritance. I am getting a fatal error of $this when not in object context. Can anyone explain me this error, what does it mean?
here is my code:
<?php
class human{
public $gender;
public function _construct($gender)
{
$this->gender=$gender;
echo $this->get_gender();
}
public function get_gender()
{
return $this->gender;
}
}
class person extends human{
public $name;
public $surname;
public static function set_name($name)
{
$this->name=$name;
}
public static function set_surname($surname)
{
$this->surname=$surname;
}
public static function get_name()
{
return $this->name;
}
public static function get_surname()
{
return $this->surname;
}
}
$john = new person('male');
$john->set_name('John');
$john->set_surname('Williams');
echo $john->get_name().' '.$john->get_surname().'is a '.$john->get_gender();
?>
There are two problems here:
You have defined your methods as static. You should not do that as they are not, they depend on being called on an object as you want to use the objects non-static properties.
You have a typo in your constructor function. The correct name for the constructor is __construct, notice the two _ at the beginning.
In a static function, $this does not exist. You can refer to the class itself with self::. So, instead of $this->surname, use self::surname. As noted below, this will change your error to a new error as it requires the variables to be declared static as well.
Of course, you really need to figure out WHY you made those functions static. Should they be static?
You're trying to access the $this property from a static method. You cannot do this, as anything static can be accessed without instantiating the class, therefore the $this variable would not make sense, as you are not in an actual class instance.
The this keyword refers to the current object you are working with, e.g. if you were to make 5 instances of person, each $this would refer to that specific instance of person, and you could change each objects properties freely.
When you use static you are not referring to any instance, you are simply accessing static variables and calling static methods of that class. All these variables and methods are 'class wide'. That means if you change the static property in one instance of the class, the static property will change in all the classes.
Another way to imagine this is, take when calling the new keyword, you create a new instance of the object. Every instance will have its own copy of all the properties and methods you describe in the class, EXCEPT for the static ones. Imagine that when you access a static method or a static property you are accessing one object always.
That's why it would not make sense to access $this from a static context. You are not referring to any specific instance, only the class itself.
I hope I've explained this well enough, it's a very important concept to grasp in OOP, and it does give some people a lot of trouble to understand the concept.

Singleton: How does static variable $instance store data

I've got a comprehension question:
The singleton design pattern uses a static function call like Singleton::getInstance() and in this function it uses static variables like self::$_instance.
According to the definition, static functions and variables are independent of any concrete instances and are evoked each time just for the purpose of it's particular call. How then is it possible, that any value can be stored in such quasi-abstract and each-time-new-created 'objects'?
Hope you understood my question.
Static property is similar to global variable. Difference only of its visibilities. Global variable can changed by everybody as public static property, but private or protected static property has less visibility.
Imaginate that class is actually an object which created when defined and could exists only in one instance. Static properties and methods are properties and methods of this "object". That is why many people does not understand differnce between regular class with static members and singleton.
Visibility, static, singleton pattern
The Singleton design (anti-)pattern allows to make sure there is at most one instance created.
The property is static, therefore it can be accessed from a static method. However the underlying object is a real, live instance. From a static method, you cannot use $this, but you can refer to any already-instanciated object, which self::$_instance happens to be)
class SingletonClass {
private static $_instance;
private $_someProperty;
public static function getSomeProperty() {
return self::$_instance->_someProperty; // allowed, self::$_instance is static, but a real object nonetheless
}
}
Three things make the class Singleton or else it will a normal class.
Static variable
Static method
Private constructor
Probably you have created a class for counter functionality, Singleton is like the same.

Categories