0

I'm writing a simple class that will create a simple log file for my site. For some reason, when I have variable file_path outside of the function, I get this error...

Parse error: parse error, expecting `','' or `';''

With this code..

class Logger {

public $file_path = SITE_ROOT.DS.'logs'.DS.'log.txt';

public static function log_action ($message="") {
    if (file_exists($file_path)) {
        file_put_contents($file_path, $message, FILE_APPEND);
    } else {
        return "could not write to log file";
    }
}

However when the variable is within the function, this error doesn't come. Why is this?

public static function log_action ($action, $message="") {
    $file_path = SITE_ROOT.DS.'logs'.DS.'log.txt';
    if (file_exists($file_path)) {
        file_put_contents($file_path, $message, FILE_APPEND);
    } else {
        return "could not write to log file";
    }
1
  • 4
    You can't use functions, operators such as concatenation, etc when defining class properties. If you want to assign a value that uses concatenation, then do so within your class constructor Commented Apr 28, 2013 at 17:08

1 Answer 1

2

Inside classes, the PHP code you can run outside methods is limited:

Class member [...] are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. 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.

From Properties.

Thus this is not valid:

public $file_path = SITE_ROOT.DS.'logs'.DS.'log.txt';
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! So how would I reuse this file path when I want to use for other functions within the class?
It'd normally be set in the constructor but, since you plan to use it in static methods, that's not an option. You'll need to set it from outside the class (it's a public property after all) or make the static method call another static method to obtain the path.

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.