Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP $this when not in object context for set public variable from out of class

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
like image 471
DolDurma Avatar asked Mar 07 '14 06:03

DolDurma


1 Answers

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
like image 200
Shankar Narayana Damodaran Avatar answered Oct 10 '22 08:10

Shankar Narayana Damodaran