Jump to content

Recommended Posts

If I have a base class MyBase:

 

class MyBase {
	public $user_id = NULL;

	 	public function __construct() {
	 		$this->user_id = "justin";
	 	}
  }

 

Then I have a class which inherits the base class MyClass:

 

class Test extends MyBase {
      public static function get_user_id() {
          echo parent::$user_id;
      }
}

 

Finally calling it:

 

    echo Test::get_user_id();

 

First question, do I have to create an instance of MyBase, or when Test extends MyBase will it instanciate it automatically and call the MyBase constructor? Second, I am getting the error:

 

PHP Fatal error:  Access to undeclared static property: MyBase::$user_id

Link to comment
https://forums.phpfreaks.com/topic/236450-oo-extends-with-a-constructor/
Share on other sites

Gizmola,

 

First, who is calling the base constructor?

 

I actually don't want to access user_id statically, but I think to use the keyword `parent` you have to use it like: parent::$user_id. Is there another way to access the property of the MyBase class $user_id from inside the Test class?

class MyBase {
                public $user_id = NULL;

                public function __construct() {
                        $this->user_id = "justin";
                }
  }

class Test extends MyBase {
      public function get_user_id() {
          echo $this->user_id;
      }
}

$t = new Test();
$t->get_user_id()

The only thing, is that I don't want Test to be an instance. It is static. So:

 

class Test extends MyBase {
      public static function get_user_id() {
          echo $this->user_id;
      }
}

 

Obviously, if its static, can't use $this. Is there a way around this?

Why do you want to call it statically? To access $user_id you need to declare it statically.

 

class MyBase {
  protected static $user_id = "justin";
}

class Test extends MyBase {
  public static function get_user_id() {
    return self::$user_id; // or static::$user_id (5.3.x+) or parent::$user_id;
  }
}

print Test::get_user_id();

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.