How to Use Attributes Using Classes in PHP?

If we are using classes than we will have variables inside the classes. These variables are called Attributes. Variable can be used any where without even class. Just put a $ sign in front of variable name and there we have a variable but if we are declaring variable inside the class then they are attributes.

Second difference is we need to set attributes with clear values not result of some expressions. That will not work.

class WorkableClass {
	public $var1 = 'abc';
	public $var2 = 100;
	public $var3 = [ 1, 2, 3 ];
}

class NotWorkableClass{
	public $var1 = get_date();
	public $square = $var1 * $var1;
}

Now you cannot also initialise attribute anywhere in your class like you used to do in public scope. For example this will not work.

class NotWorkableClass{
	public $num = 2;
	public $square;
	$square = $num * $num;
}

Now in classes we cannot write code anywhere as we want. If we want to do some operations then we have to write code in functions. Remember operations are some verb so for that make a function.

class WorkableClass {
	public $num = 2;
	public $square;

	public function getSquare() {
		$square = $num * $num;
	}
}

Now this makes sense but it will not work. Functions in class cannot access class attributes as we can use in public scope. We need to use $this keyword. So working code is written below.

class WorkableClass{
	public $num = 2;
	public $square;

	public function getSquare(){
		$this->square = $this->num * $this->num;
	}
}

Do not worry about $this keyword. It is used when we want to use when we work with attributes in same class.