Can we access properties without $this? - php

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.

Related

How to hide some fields through a trait in Laravel [duplicate]

I have this method that I want to use $this in but all I get is: Fatal error: Using $this when not in object context.
How can I get this to work?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
This is the correct way
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
Use self:: instead of $this-> for static methods.
See: PHP Static Methods Tutorial for more info :)
You can't use $this inside a static function, because static functions are independent of any instantiated object.
Try making the function not static.
Edit:
By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Only static functions can be called within the static function using self:: if your class contains non static function which you want to use then you can declare the instance of the same class and use it.
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
The accessor this refers to the current instance of the class. As static methods does not run off the instance, using this is barred. So one need to call the method directly here. The static method can not access anything in the scope of the instance, but access everything in the class scope outside instance scope.
It's a pity PHP doesn't show a descriptive enough error. You can not use $this-> inside a static function, but rather use self:: if you have to call a function inside the same class
In the static method,properties are for the class, not the object.
This is why access to static methods or features is possible without creating an object.
$this refers to an object made of a class, but $self only refers to the same class.
Here is an example of what happens when a method of a class is called in a wrong way. You will see some warnings when execute this code but it will work and will print: "I'm A: printing B property". (Executed in php5.6)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
It seams that the variable $this, used in a method which is called as a static method, points to the instance of the "caller" class. In the example above there is $this->property used in the A class which points to a property of the B.
EDIT:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
PHP > The Basics

PHP late static binding scope confusion

From PHP mannual second paragraph, it says that:
static:: introduces its scope.
I tried the following example accordingly:
class Father {
public function test(){
echo static::$a;
}
}
class Son extends Father{
protected static $a='static forward scope';
public function test(){
parent::test();
}
}
$son = new Son();
$son->test(); // print "static forward scope"
It works as described. However, the following example will raise a fatal error:
class Father {
public function test(){
echo static::$a;
}
}
class Son extends Father{
private static $a='static forward scope';
public function test(){
parent::test();
}
}
// print "Fatal erro: Cannot access private property Son::$a"
$son = new Son();
$son->test();
My main question is how to interpret the word scope here? If static introduces Son's scope to Father, then why private variables are still invisible to Father?
Are there two things variable scope and visibility scope? I'm new to PHP sorry if this sounds funny.
There are two things at play here: scope and visibility. Both together decide if you can access the property.
As you found in your first test, late static binding lets $a be available in the scope of the Father class. That simply means the variable (not necessarily its value) is "known" to this class.
Visibility decides whether the variables in scope can be accessed by particular classes and instances. A private property is only visible to the class in which it is defined. In your second example, $a is defined private within Son. Whether or not any other class is aware it exists, it can not be accessed outside of Son.
static makes $a a property which is known to Father, but the property's visibility decides whether or not its value can be accessed.
As a test to further help understand it, try using self instead of static. You'll get back a different error that $a is not a property of Father.

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.

Call a private $var via a static method in php without instanciating any object [duplicate]

I have this method that I want to use $this in but all I get is: Fatal error: Using $this when not in object context.
How can I get this to work?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
This is the correct way
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
Use self:: instead of $this-> for static methods.
See: PHP Static Methods Tutorial for more info :)
You can't use $this inside a static function, because static functions are independent of any instantiated object.
Try making the function not static.
Edit:
By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Only static functions can be called within the static function using self:: if your class contains non static function which you want to use then you can declare the instance of the same class and use it.
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
The accessor this refers to the current instance of the class. As static methods does not run off the instance, using this is barred. So one need to call the method directly here. The static method can not access anything in the scope of the instance, but access everything in the class scope outside instance scope.
It's a pity PHP doesn't show a descriptive enough error. You can not use $this-> inside a static function, but rather use self:: if you have to call a function inside the same class
In the static method,properties are for the class, not the object.
This is why access to static methods or features is possible without creating an object.
$this refers to an object made of a class, but $self only refers to the same class.
Here is an example of what happens when a method of a class is called in a wrong way. You will see some warnings when execute this code but it will work and will print: "I'm A: printing B property". (Executed in php5.6)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
It seams that the variable $this, used in a method which is called as a static method, points to the instance of the "caller" class. In the example above there is $this->property used in the A class which points to a property of the B.
EDIT:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
PHP > The Basics

Using $this inside a static function fails

I have this method that I want to use $this in but all I get is: Fatal error: Using $this when not in object context.
How can I get this to work?
public static function userNameAvailibility()
{
$result = $this->getsomthin();
}
This is the correct way
public static function userNameAvailibility()
{
$result = self::getsomthin();
}
Use self:: instead of $this-> for static methods.
See: PHP Static Methods Tutorial for more info :)
You can't use $this inside a static function, because static functions are independent of any instantiated object.
Try making the function not static.
Edit:
By definition, static methods can be called without any instantiated object, and thus there is no meaningful use of $this inside a static method.
Only static functions can be called within the static function using self:: if your class contains non static function which you want to use then you can declare the instance of the same class and use it.
<?php
class some_class{
function nonStatic() {
//..... Some code ....
}
Static function isStatic(){
$someClassObject = new some_class;
$someClassObject->nonStatic();
}
}
?>
The accessor this refers to the current instance of the class. As static methods does not run off the instance, using this is barred. So one need to call the method directly here. The static method can not access anything in the scope of the instance, but access everything in the class scope outside instance scope.
It's a pity PHP doesn't show a descriptive enough error. You can not use $this-> inside a static function, but rather use self:: if you have to call a function inside the same class
In the static method,properties are for the class, not the object.
This is why access to static methods or features is possible without creating an object.
$this refers to an object made of a class, but $self only refers to the same class.
Here is an example of what happens when a method of a class is called in a wrong way. You will see some warnings when execute this code but it will work and will print: "I'm A: printing B property". (Executed in php5.6)
class A {
public function aMethod() {
echo "I'm A: ";
echo "printing " . $this->property;
}
}
class B {
public $property = "B property";
public function bMethod() {
A::aMethod();
}
}
$b = new B();
$b->bMethod();
It seams that the variable $this, used in a method which is called as a static method, points to the instance of the "caller" class. In the example above there is $this->property used in the A class which points to a property of the B.
EDIT:
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).
PHP > The Basics

Categories