0

I have a static field in a class with a regex. This regex requires a list of values that are in a static array, so I create a static function that returns the group (e.g. (a|b|c|d)) to be inserted in the regex. Problem is that I can't call a static function when I declare a static field.

I would need to put the value returned by the function inside the field.

Example:

class A {
    public static function Foo()
    {
        return "Foo";
    }

    public static $Bar = "lol". self::Foo();
}

echo A::$Bar;

I get

Parse error: syntax error, unexpected '(', expecting ',' or ';' on line 7

How can I solve that?

7
  • Why you use self::Foo() ? instead Foo() Commented Apr 15, 2015 at 10:56
  • that ain't possible in PHP, when setting properties, they need to be simple declarations. php.net/manual/en/language.oop5.properties.php. its stated in the first paragraph Commented Apr 15, 2015 at 10:56
  • 1
    You can't, you use echo A::$Foo(); instead Commented Apr 15, 2015 at 10:58
  • The workround is to use echo A::$Foo(); instead, as I already said Commented Apr 15, 2015 at 11:05
  • The result of Foo() is just a part of the string which is in Bar, I will edit the question Commented Apr 15, 2015 at 11:10

2 Answers 2

1

You can't initialize a static property with "dynamic" values. You can only initialize it with a literal or a constant.

You can also see this in the manual:

Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object.

If you want to use the static function just use it like this:

echo A::Foo();
Sign up to request clarification or add additional context in comments.

1 Comment

@Phate01 No, you can't assign the static method to the property. (Just added how you use your static method)
0

Rather than trying to do something in a way that the language doesn't permit, reverse your thinking and do it in a way that the language will allow:

class A {
    public static function Foo()
    {
        return "lol" . self::$Bar;
    }

    public static $Bar = "Foo";
}

echo A::Foo();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.