What is wrong with this code ?

Discussion in 'PHP' started by lagna, Sep 24, 2012.

  1. #1
    class MyClass
    {
    protected $_MyMember;


    public function __construct()
    {
    $this->_MyMember = 1;
    }


    public static function getNewthingStatic()
    {
    return $this->_MyMember * 5; // here's the catch
    }
    }
     
    lagna, Sep 24, 2012 IP
  2. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #2
    if you remove the static keyword in the method declaration it will work. Not quite sure though.
     
    plussy, Sep 24, 2012 IP
  3. plussy

    plussy Peon

    Messages:
    152
    Likes Received:
    5
    Best Answers:
    9
    Trophy Points:
    0
    #3
    oh by the way I only found it out because I checked the error log. always good checking it ;)
     
    plussy, Sep 24, 2012 IP
    dushmant likes this.
  4. dushmant

    dushmant Guest

    Messages:
    3
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Static methods don't have access to $this, because static methods can be executed without instantiating a class.
     
    dushmant, Sep 24, 2012 IP
  5. pxranger

    pxranger Peon

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Were you having a problem with your code somewhere, or just posting to see if people could figure it out?
     
    pxranger, Sep 24, 2012 IP
  6. YoEli

    YoEli Peon

    Messages:
    14
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    dushmant <-- correct answer, don't use $this in a static function for a class.
     
    YoEli, Sep 24, 2012 IP