PHP $this when not in object context for set publi

2020-03-23 02:58发布

问题:

I have simple class and I want to set public variable from out of class.

<?php

class AlachiqHelpers
{
    public $height;

    public static function getHeight($height)
    {
        return $this->height - 50;
    }

    public static function setHeight($height)
    {
        $this->height = $height;
    }
}

In Result i get this error:

Using $this when not in object context

回答1:

The $this keyword cannot be used under static context !.

Case 1:

You need to remove the static keyword from the function defintion.

Instead of

public static function setHeight( $height ){

Should be

public function setHeight( $height ){

Case 2:

If you really need to make it(function) as static... You could just use the self keyword to access the variable..

public static $height;
public static function setHeight( $height )
{
    self::$height=22;
}

Keep in mind that the $height variable is also made static


The working code.. (static one)

<?php
class AlachiqHelpers
{
    public static $height;
    public function getHeight()
    {
        return self::$height - 50;
    }

    public static function setHeight($height1)
    {
        self::$height = $height1;
    }
}

$a = new AlachiqHelpers();
$a->setHeight(180);
echo $a->getHeight();

OUTPUT :

130


回答2:

Remove static, these methods should not be static method but instance method.

$this can not be used under static context, because static context is shared by all the instances but not a single one.

Static method can only access the static property.

Non-static method can access both non-static property (by $this->foo) and static property(by self::$foo).



回答3:

Source

Because static methods are callable without an instance of the object created, the pseudo-variable $this is not available inside the method declared as static.

You can't use $this inside a static function, because static functions are independent of any instantiated object.

Try making the function not static.

public  function setHeight( $height ){

        $this->height=$height;

    }