Access constant of a class member object doesn't work

74 Views Asked by At

if I try the following example (PHP 5.4) I get the following error:

Parse error: syntax error, unexpected '::' (T_PAAMAYIM_NEKUDOTAYIM), expecting ',' or ';'

class a {
    public $p;
    public function __construct() {
        $this->p = new b;
    }
    public function giveout() {
        echo $this->p::c;
    }
}
class b {
    const c = '234';
}
$obj = new a;
$obj->giveout();

But why? Isn't it possible to use the double colon and arrow in one expression? I know I could also use a getter method in class b and then call $this->p->get(), but I'd rather like to use the above syntax.

1

There are 1 best solutions below

1
On

Rewrite

echo $this->p::c;

to

echo $this->p=b::c;

and..

$a->giveout();

to

$obj->giveout();


Putting it all together...

<?php
class a {
public $p;
public function __construct() {
$this->p = new b;
}
public function giveout() {
echo $this->p=b::c;
}
}
class b {
const c = '234';
}
$obj = new a;
$obj->giveout();

OUTPUT :

234