In php, is there any difference between using
$myClass::method()
and
$myClass->method()
What's the reason for the change? (I believe -> has been around longer.)
I could see a point of using :: for methods and -> for properties or vice versa.
:: is the scope resolution operator, used for accessing static members of classes.
-> is the member operator, used for access members of objects.
Here's an example:
class Car {
public $mileage, $current_speed, $make, $model, $year;
public function getCarInformation() {
$output = 'Mileage: ' . $this->mileage;
$output = 'Speed: ' . $this->current_speed;
$output = 'Make: ' . $this->make;
$output = 'Model: ' . $this->model;
$output = 'Year: ' . $this->year;
return $output;
}
}
class CarFactory {
private static $numberOfCars = 0;
public static function carCount() {
return self::$numberOfCars;
}
public static function createCar() {
self::$numberOfCars++;
return new Car();
}
}
echo CarFactory::carCount(); //0
$car = CarFactory::createCar();
echo CarFactory::carCount(); //1
$car->year = 2010;
$car->mileage = 0;
$car->model = "Corvette";
$car->make = "Chevrolet";
echo $car->getCarInformation();
Consider this:
class testClass {
var $test = 'test';
function method() {
echo $this->test;
}
}
$test = new testClass();
$test->method();
testClass::method();
The output will be something like:
test
Fatal error: Using $this when not in object context in ... on line 7
This is because :: makes a static call to a class while -> is used to call methods or properties on a specific instance of a class.
Incidentally, I don't believe you can do $test::method() because PHP will give you a parse error like this:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM in ... on line 14
:: is also used within a class/object to call its parent, e.g.:
parent::__constructor();
Also if it's called from within an object (so not statically).
Related
I need to access a constant that belongs to a class, but instead of writing the class' name explicitly, I want to retrieve it from the object directly. The object is a property of another object.
$this->fetcher::BASE_URL
This statement produces the error syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM)
Here's an ugly work-around....
<?php
class simpleClass {
public function __construct() {
$this->fetcher = new simpleClass2();
}
public function printBaseURL() {
$fetcher = $this->fetcher;
print 'Base URL: ' . $fetcher::BaseUrl;
}
}
class simpleClass2 {
const BaseUrl = 'one';
}
$simpleClass = new simpleClass();
$simpleClass->printBaseURL();
You could use a function to return the constant
class MyClass
{
function getConstant() {
return self::CONSTANT . "\n";
}
}
Then call that function
$class = new MyClass();
$class->getConstant();
Or simply call the constant
MyClass::CONSTANT;
You can find more information about accessing constants within classes here. Look at the "user contributed notes", very good examples with explanation there.
I have trouble accessing a constant of a class via the object operator(->).
I have these 2 classes:
class withConstant {
const MY_CONSTANT = 5;
}
class usingConstant {
public $class = null;
function __construct() {
$this->class = new withConstant();
}
}
When I do this:
$myClass = new usingConstant();
echo $myClass->class::MY_CONSTANT;
I get an error Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM). However, I can get around it with this:
$myClass = new usingConstant();
$myClass = &$myClass->class;
echo $myClass::MY_CONSTANT;
I prefer to access the constant without assigning the member variable to another variable first.
This is the closest I can come to what you're actually after achieving unfortunately:
echo constant(get_class($myClass->class).'::MY_CONSTANT');
Note that this is incredibly inefficient, since it looks up the class to determine it's name, then looks it up again to reference the constant.
You can make a getter function in withConstant and call that.
class withConstant {
const MY_CONSTANT = 5;
function getConstant(){
return self::MY_CONSTANT;
}
}
Then you can call that function:
$myClass = new usingConstant();
echo $myClass->class->getConstant();
Is it possible to store a reference to an object's property (class member variable which holds a scalar data such as string or integer) within an object of a different class?
I am trying to have the following two echo statements produce identical results.
<?php
$x = new Type;
$x->name = 'abcd';
echo "x.name=" . $x->name . '<br/>';
echo "x.obj.name=" . $x->obj->value . '<br/>';
class Type
{
public $obj; //Instance of Property (Property class defined below)
public $name;
function __construct()
{
$this->obj = new Property($this->name);
}
}
class Property
{
public $value;
function __construct($v)
{
$this->value = $v;
}
}
$this->obj = new Property($this->name);
Is called at the time of object creation. Which is executed before the assignment.
i.e.
When you call $x = new Type;
The constructor is called and you try to copy 'name' which is empty by then
May be what you want it following, rather than passing the value, pass $this and keep the referance.
<?php
class Type
{
public $obj; //Instance of Property (Property class defined below)
public $name;
function __construct()
{
$this->obj = new Property($this);
}
}
class Property
{
public $value;
function __construct($ref)
{
$this->value = $ref;
}
}
$x = new Type;
$x->name = 'abcd';
echo "x.name=" . $x->name . '<br/>';
echo "x.obj.name=" . $x->obj->value->name . '<br/>';
You can pass the name value inside the constructor.
$x = new Type('abcd');
Without doing that, your constructor will not know what $this->name is yet. So we use it in the constructor and set the classes property before using it.
function __construct($p_name){
$this->name = $p_name;
$this->obj = new Property($this->name);
}
You could just as easily set the value after calling the constructor and then initialize the reference afterwards -
class Type {
public $obj;
public $name;
function setProperty(){
$this->obj = new Property($this->name);
}
}
$x = new Type;
$x->name = 'abcd';
$x->setProperty();
echo "x.name=" . $x->name;
echo "x.obj.name=" . $x->obj->value;
This is an old question but just to add to this.
You can have an object with methods and properties inside of another object..
Example
$obj1 = new class1();
$obj2 = new class2($obj1); // you just grabbed $obj1 and stuck it inside $obj2
Now you can use the stored object's methods like so:
$obj2->obj1->method_from_obj1();
or access the stored object's properties like so:
$obj2->obj1->property_of_obj1;
This is SUPER convenient if you instantiated an object of some API and want to use the API methods inside of your own object.
While at the time of answering this question is 9+ years old, I've encountered a similar issue today and found a way to do what's requested.
In short: you should use references. Here's a a working example (PHP 8):
<?php
class Source
{
public int $counter = 10;
}
class Consumer
{
public int $value = 0;
public function __construct(int &$value)
{
$this->value = &$value;
}
}
$source = new Source();
// Pass property of Source instance to the consumer.
$consumer = new Consumer($source->counter);
assert($consumer->value === 10);
// Changing value in the Source instance.
$source->counter = 15;
// ... and value in the consumer updated as well.
assert($consumer->value === 15);
exit;
So, the answer is yes, it is possible.
If I have an instance in PHP, what's the easiest way to get to a static property ('class variable') of that instance ?
This
$classvars=get_class_vars(get_class($thing));
$property=$classvars['property'];
Sound really overdone. I would expect
$thing::property
or
$thing->property
EDIT: this is an old question. There are more obvious ways to do this in newer
PHP, search below.
You need to lookup the class name first:
$class = get_class($thing);
$class::$property
$property must be defined as static and public of course.
From inside a class instance you can simply use self::...
class Person {
public static $name = 'Joe';
public function iam() {
echo 'My name is ' . self::$name;
}
}
$me = new Person();
$me->iam(); // displays "My name is Joe"
If you'd rather not
$class = get_class($instance);
$var = $class::$staticvar;
because you find its two lines too long, you have other options available:
1. Write a getter
<?php
class C {
static $staticvar = "STATIC";
function getTheStaticVar() {
return self::$staticvar;
}
}
$instance = new C();
echo $instance->getTheStaticVar();
Simple and elegant, but you'd have to write a getter for every static variable you're accessing.
2. Write a universal static-getter
<?php
class C {
static $staticvar = "STATIC";
function getStatic($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->getStatic('staticvar');
This will let you access any static, though it's still a bit long-winded.
3. Write a magic method
class C {
static $staticvar = "STATIC";
function __get($staticname) {
return self::$$staticname;
}
}
$instance = new C();
echo $instance->staticvar;
This one allows you instanced access to any static variable as if it were a local variable of the object, but it may be considered an unholy abomination.
classname::property;
I think that's it.
You access them using the double colon (or the T_PAAMAYIM_NEKUDOTAYIM token if you prefer)
class X {
public static $var = 13;
}
echo X::$var;
Variable variables are supported here, too:
$class = 'X';
echo $class::$var;
You should understand what the static property means. Static property or method is not for the objects. They are directly used by the class.
you can access them by
Class_name::static_property_name
These days, there is a pretty simple, clean way to do this.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
//...
public function __toString()
{
return self::class;
}
}
echo Bar::$baz; // returns 1
$bar = new Bar();
echo $bar::$baz; // returns 1
You can also do this with a property in PHP 7.
<?php
namespace Foo;
class Bar
{
public static $baz=1;
public $class=self::class;
//...
}
$bar = new Bar();
echo $bar->class::$baz; // returns 1
class testClass {
public static $property = "property value";
public static $property2 = "property value 2";
}
echo testClass::$property;
echo testClass::property2;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
From the string name of a class, can I get a static variable?
Somewhere in a parent class, I need to find the value of a static variable of one of the possible child classes, determined by the current instance.
I wrote:
$class = get_class($this);
$value = isset($class::$foo['bar']) ? $class::$foo['bar'] : 5;
In this example, the subclass whose name is in $class has a public static $foo.
I know using $class::$foo['bar'] is not a very beautiful piece of code, but it gets the job done on PHP 5.3.4.
In PHP 5.2.6 though, I am getting a syntax error:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ',' or ')'
Is there an alternative way that would work on PHP 5.2.4+ that would get the same thing done?
EDIT: Reflection is better.
You can try the get_class_vars method. No access to PHP 5.2.6, but this works in 5.2.11...
class Test {
public static $foo;
function __construct() {
echo("...Constructing...<br/>");
Test::$foo = array();
Test::$foo['bar'] = 42;
}
function __toString() {
return "Test";
}
}
$className = 'Test';
$class = new $className();
$vars = get_class_vars($className);
echo($vars['foo']['bar'] . "<br/>");
Output:
...Constructing...
42
The reason that this does not work in PHP 5.2, is because before PHP 5.3 you are not allowed to use variables in the classname. So, if possible use eval for this.
eval('$result = ' . $c . '::$foo[\'bar\'];');
echo $result;
Otherwise, you're forced to use a function in the child class to receive the value. For example:
class MyParent {
public function __construct() {
$var = $this->_getVariable();
echo $var['bar'];
}
}
class MyChild extends MyParent {
static $var = array('bar' => 'foo');
protected function _getVariable() {
return self::$var;
}
}
new MyChild();
class Bar1 {
static $var = array('index' => 'value');
}
class Bar2 extends Bar1 {
}
class Foo extends Bar2 {
static $var = array('index' => 'value in Foo');
public function __construct() {
echo parent::$var['index'];
}
}
$foo = new Foo();
will output 'value', but not 'value in Foo'
Hope, that's what you are looking for.
You can get class static/call static method in the class you are working in using self key word or for parent class using parent. You can get that error on php 5.2.6 because of changes in get_class function in PHP 5.3.0