1

I am trying to access the variables from the parent class as shown below:

 //PARENT CLASS
class InfoString{
    private $username = "JOE";

    public function _construct(){}

    protected function get_username(){
        return $this->username;
    }         
}


class Service extends InfoString{
    //this class should now inherit the variables in InfoString, right??
    public function _construct(){}

    public function hello_username(){
        echo "HELLO! ". parent::get_username(); 
    }
}

and I call the class like so:

$a = new Service();
$a->hello_username(); //prints nothing, instead of the username

Instead of getting "HELLO! JOE", I get an empty string. What am I doing wrong here?

Also, suppose the class 'InfoString' will contain configuration parameters - is it a good idea to extend this class, or what would be the proper implementation to get the config variables from, say class 'InfoString' into another class???

Thanks.

5
  • 1
    codepad.viper-7.com/wqiKSF Commented Jan 28, 2012 at 6:48
  • No, Its correct, make sure where you have write your code. Seems There are no any errors. Commented Jan 28, 2012 at 6:50
  • Didn't find any wrong with your code. Its run very well in my server and print the desire output. Commented Jan 28, 2012 at 6:52
  • Must be something else in my code then. I ll double check. What about my question on using config file as parent class? Is this good OOP design or not? Commented Jan 28, 2012 at 6:55
  • @J.J. i think i'm not good. Hope you are well. Commented Jan 28, 2012 at 7:01

1 Answer 1

2

You're just extending InfoString, so you can just use $this->get_username(); and it will work fine. :: is for calling static methods.

Also, you'd get an error if you'd increase your error level. Call error_reporting(E_ALL); this will give you clues to solve similar issues in the future.

Sign up to request clarification or add additional context in comments.

Comments

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.