Cannot access class constant from an instance using the :: scope operator

Viewed 14047

I hit a strange problem today and even as a PHP engineer i'm stumped at this:

It seems you can access a class constant from an object instance such as:

class a {
    const abc = 1;
}
$a = new a();
var_dump($a->abc);

This will output null instead of the expected 1. I was able to do the following:

class a {
    const abc = 1;
}
$a = new a();
var_dump(a::abc);

But in the context of a sub object that doesn't really know who the parent is exactly, i find it extremely annoying to do:

class a {
    const abc = 1;
}
$a = new a();
$c = get_class($a);
var_dump($c::abc);

Is it me or this is completly stupid, if not, please enlighten me why its working that way.

EDIT

Another way of doing it but it's not really better:

class a {
    const abc = 1;
}
class b {
    public function getA(){
        return new a();
    }
}
$b = new b();
$c = $b->getA();
var_dump($c::abc);

This last example works more like what i am doing and experiencing...

6 Answers

I know this is an old thread, but for people who want to know the best way to do this have a look at the PHP function constant().

With constant() you can simply do this:

$a = new a();
$value = constant(get_class($a)."::abc");
// $value === 1

this has been available since PHP 4, and still works perfectly in PHP 5.5

When trying to use const defined in a class inside a different namespace, the Scope Resolution Operator (::) can be used without problems as stated by the docs prefixing the namespace before the class in which the const was declared with this format:

  • (<namespace>"\")*<className>::<const>

With the next namespace, class and const definitions:

models/OperationModel.php

<?php
namespace models;

class OperationModel {
  const OPERATION_INITIALIZING = 1;
}

You can use the const from another namespace\class like this:

controllers/MobileController.php

<?php
namespace controllers;

use models\OpertionModel;

class MobileController {
  private function thingy() {
    $operation_status = models\OperationModel::OPERATION_INITIALIZING;
  }
}
Related