Pregunta

Rather than having multiple lines of the same code on each method, I want to set up a (Boot/initialization) method to define common values and such. Then, call that method when needed.

Initially, I had something like this:

<?php
class boot {
    private static $root = $_SERVER['DOCUMENT_ROOT'] . '/';


    public static function load() {
        return self::$root;
    }
}

$test = boot::load();
echo $test;
?>

But I would get an error saying something like: Parse error: syntax error, unexpected T_VARIABLE in...

So, I changed it to:

<?php /* Class Bootstrap (Boot for short) */
class boot {
    private static $base = null;
    private static $root = null;


    private static function boot(){
        self::$base = $_SERVER['DOCUMENT_ROOT'] . '/';
    }


    public static function load() {
        self::boot();
        return self::$base;
    }
}

$test = boot::load();
echo $test;
?>

Then I got this: Fatal error: Constructor boot::boot() cannot be static in...

So I resorted to:

<?php
class boot {
    private static $base = null;
    private static $root = null;


    private function boot(){
        $this->base = $_SERVER['DOCUMENT_ROOT'] . '/';
    }


    public static function load() {
        $this->boot();
        return self::$base;
    }
}

$test = boot::load();
echo $test;
?>

But I am still geting an error, Fatal error: Using $this when not in object context in... I tried different things but I am out of ideas.

¿Fue útil?

Solución 2

Try the following

class boot {
    private static $base = null;
    private static $root = null;

    public static function load() {
        self::$base = $_SERVER['DOCUMENT_ROOT'] . '/';
        return self::$base;
    }
}

$test = boot::load();
echo $test;

Otros consejos

You cannot use $ this in a static context.

When to use self over $this?

To sum up the above answer you have to use $this To access the members that belong to the current Object (non-static) but use self :: to access the class's static members.

You could make all your functions static and use self :: instead of $this-> .

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top