PHP class: Global variable vs Accessbale varibales [duplicate] - php

This question already has answers here:
What does PHP keyword 'var' do?
(8 answers)
Closed 6 years ago.
I have a doubt what is the difference between below class.
class Test {
var $location;
public function __construct() {
$this->location = 'India';
}
}
class Test {
protected $location;
public function __construct() {
$this->location = 'India';
}
}
Why we use var ? What is the purpose of using var as global here.??
Please clarify me.

The keyword before variable name defines the visibility of the variable. It defines the access rights for the particular variable.
var
When using var, it will be publicly accessible through out your project same as public.
protected
When using protected, variable is only accessible for the classes which extends parent class for particular page only.
Note: The PHP 4 method of declaring a variable with the var keyword is still supported for compatibility reasons (as a synonym for the public keyword). In PHP 5 before 5.1.3, its usage would generate an E_STRICT warning.
Read More Here

Related

static keyword before variable in a method [duplicate]

This question already has answers here:
Static variables in PHP
(5 answers)
Closed 11 months ago.
I found the following method and I don't know what the static keyword does at that point. The variable is initialized with [] so it's empty anytime the method is called anyways.
What does the static keyword do at this point?
public function getSomething($entity)
{
static $collection = [];
if (!$collection[$entity->getPrimaryKey()]) {
$collection[$entity->getPrimaryKey()] = 'something';
}
return $this->doCollection($collection);
}
declaring properties or methods as static allows you to access them without needing to instantiate the class.

Calling static functions with $this [duplicate]

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

instance object can call static method but not static variable [duplicate]

This question already has answers here:
PHP: What if I call a static method in non-static way
(3 answers)
Closed 6 years ago.
I am trying to wrap my head around the static keyword in PHP. Here I wrote a small piece of code where my person1 instance of Human can call a static method called sayRealname(). But when I try to call a public static variable it gives an error. What is the reason for that?
class Human{
public static $age=34;
public static $name='humpty dumpty';
protected static $realname='al';
public static function sayRealname(){
echo self::$age;
}
}
$person1=new Human();
echo $person1->name; // error
$person1->sayRealname(); // prints 34
When you're accessing static content, you need to use the static operator ::.
On the other hand, the arrow operator -> is meant to be used in an instance context, which belongs to the particular instance upon it's being called.
You can read more about this in this part of the documentation.

Class Property Containing a Global Variable [duplicate]

This question already has answers here:
PHP class: Global variable as property in class
(8 answers)
Closed 9 years ago.
I want to know if there is a way to store a global variable inside a class property so that it can be easily used by methods inside the class.
for example:
$variableGlobal = 30;
Class myClass{
public $classProperty = global $variableGlobal;
function myFunction(){
$accessible = $this->classProperty;
}
now I know I can get the global variable by simply calling for it in the class function like so:
function myfunction(){
global $variableGlobal;
}
I thought something like what I want in example 1 existed in but I could be flat out wrong, or I am right but I am approaching this the complete wrong way. Any ideas would be great thanks.
Forgot to mention alternatively I would be happy not to use a global and instead store the results of another class function inside the class variable
like so:
public $var = OtherClass::ClassFunction();
The value you want should be available anywhere in the GLOBALS variable using the variable name as the key.
public $classProperty = GLOBALS[$variableGlobal]
However, I would suggest, to avoid unnecessary coupling and allow for testing, you may want to pass the value in the global in to the class.
You can use the construct method and pass by reference. Inject the value to the constructor when you instantiate the class, and by using reference operator &, you can access the global variable at any time and pick up the current value.
You can also just access the global via $GLOBAL structure within the class. See the example here:
<?php
$variableGlobal = 30;
class myClass{
public $classProperty;
public function __construct(&$globalVar){
$this->classProperty = &$globalVar;
}
public function myFunction(){
$accessible = $this->classProperty;
// do something interesting
print "$accessible\n";
}
public function accessGlobal(){
print $GLOBALS["variableGlobal"] . "\n";
}
}
$thisClass = new myClass($variableGlobal);
$thisClass->myFunction();
$GLOBALS["variableGlobal"] = 44;
$thisClass->myFunction();
$variableGlobal = 23;
$thisClass->accessGlobal();
Recommended reading
References Explained
GlOBALS Explained
Figured it out, used a solution to solve my problem from another question:
PHP class: Global variable as property in class

What does $this mean in PHP? [duplicate]

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?

Categories