Using variables from parent class

Okay, this was (for me) kinda hard to figure out. Here’s what I needed: I wanted to access a variable. Not just any variable. A variable from a parent class. And I wanted it to store the information and be able to access it from anywhere. The information should not just be accessible to the extended class but also to the parent class. So I stumbled upon static.

It was a long way until i figured it: Once I declare a variable to be static$this-> isn’t going to work anymore. So I had to use self:: and parent::. What confused me is, that on the internet people also declare functions to be static. That gave me tons of errors. So here’s what worked for me:

<?php
	class A {
		public static $v;
		
		function x() {
			self::$v = "Hello";
		}
	}
	
	class B extends A{
		function y(){
			parent::$v .= " World";
		}
	}
	
	$B = new B();
	
	// Since B extends A, x() (if public)
	// is also available via $B
	$B->x();
	$B->y();
	
	// Access $v either via $B::
	//or via A:: (note the missing $)
	echo $B::$v;

Note that, if public, you must access $v via :: too! The example will output Hello World.

It was a long way for me to get here. I hope it helps you a bit if you have the same issue.

Leave a Reply

Your email address will not be published. Required fields are marked *