Search code examples
phpvisual-studio-codeintelephense

Accessing a class constant from a trait in php gives error in VScode


I have in laravel inside the same App folder a class and a trait

MyClass.php

<?php

namespace App;

class MyClass {

    use myTrait;
    CONST MY_CONST = 'CONST';
    
    public function showConst() {
        echo $this->myTraitMethod();
    }
    
}

MyTrait.php

<?php

namespace App;

class MyTrait {
    
    public function myTraitMethod() {
        return self::MY_CONST; // Undefined class constant 'MY_CONST'
        return static::MY_CONST; // Undefined class constant 'MY_CONST'
        return MyClass:MY_CONST; // This is the only one that works but I'm forcing the class name
    
    }
}

the issue is that I cannot access MY_CONST except if I force the parent class name that is not a solution for me.

The issue is just with vscode, I mean the code runs fines with both self and static but vscode returns the error

Undefined class constant 'MY_CONST'

Solution

  • So after I understood that the issue was just in vscode, I found that is a known issue of Intelephense due the fact that in older php versions, constants could not be declared in php traits

    https://github.com/bmewburn/vscode-intelephense/issues/2024

    the solution is to suppress the message using /** @disregard P1012 */ on top like this

    MyTrait.php

    <?php
    
    namespace App;
    
    class MyTrait {
        
        public function myTraitMethod() {
            /** @disregard P1012 */
            return self::MY_CONST;
        }
    }