0

I'm trying to make a debugging class for one of my websites, something similar to the logger class in Java.

<?php

abstract class DebugLevel
{
    const Notice = 1;
    const Info = 2;
    const Warning = 4;
    const Fatal = 8;
}

class Debug
{
    private static $level = DebugLevel::Fatal | DebugLevel::Warning | DebugLevel::Info | DebugLevel::Notice;


}

?>

I get a Parse error:

Parse error: syntax error, unexpected '|', expecting ',' or ';' in (script path) on line 13  

What's wrong?

1 Answer 1

3

You can't add logic to a class property (variable) or constant in PHP.

From the documentation:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.


To set such a value use the __construct() function.

class Debug {

    public $level; // can not be a constant if you want to change it later!!!

    public function __construct() {
        $this->level = DebugLevel::Fatal | DebugLevel::Warning | DebugLevel::Info | DebugLevel::Notice;
    }

}

or maybe more elegant:

class Debug {

    public $level; // can not be a constant if you want to change it later!!!

    public function setLevel($level) {
        $this->level = $level;
    }

}

Then you can call this by:

$Debug = new Debug();
$Debug->setLevel(DebugLevel::Warning);
Sign up to request clarification or add additional context in comments.

3 Comments

So how can I do what I'm trying to do?
@RiccardoBestetti: Use the __construct() function. We don't appreciate spoon-feeders here. Using __construct() is very straightforward.
When I posted the comment, he hadn't already written to use __construct().

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.