PHP : Upgrading from 7.4 to 8.1


In php 8.1, Object instantiation does not call the constructor when defiend as 

	Class MyClassName {
		function MyClassName() {}

with php 7.4, this worked.

So we need to add the constructor, __construct()

See https://www.php.net/manual/en/language.oop5.decon.php
Identifying -

Old-style constructors

Prior to PHP 8.0.0, classes in the global namespace will interpret a method named the same as the class as an old-style constructor. That syntax is deprecated, and will result in an E_DEPRECATED error but still call that function as a constructor. If both __construct() and a same-name method are defined, __construct() will be called.

In namespaced classes, or any class as of PHP 8.0.0, a method named the same as the class never has any special meaning.

Always use __construct() in new code.


The Code : myObject.php


class myOjbect{

	var $var1="Variable 1";
	var $var2="Variable 2";
	var $var3="Variable 3";
	var $var4="Variable 4";

	function myOjbect($var1=2000,$var2=false,$var3=false,$var4=false){

		$this->var1 = $var1;
		if ($var2) $this->var2 = $var2;
		if ($var2) $this->var3 = $var3;
		if ($var2) $this->var4 = $var4;
	}

	function returnIt(){
		echo "Class Data : "; 
		echo "\n";

		echo "  var1 : "; 
		echo $this->var1;
		echo "\n";

		echo "  var2 : "; 
		echo $this->var2;
		echo "\n";

		echo "  var3 : "; 
		echo $this->var3;
		echo "\n";

		echo "  var4 : "; 
		echo $this->var4;
		echo "\n";
	}

}
	

Test 1

With
	$myOjbect1= new myOjbect();
	$myOjbect1->returnIt();
We expect
	var1 = "2000"
We get
Class Data : 
  var1 : 2000
  var2 : Variable 2
  var3 : Variable 3
  var4 : Variable 4

Test 2

With
	$myOjbect2= new myOjbect(2023);
	$myOjbect2->returnIt();
We expect
	var1 = "2023"
We get
Class Data : 
  var1 : 2023
  var2 : Variable 2
  var3 : Variable 3
  var4 : Variable 4

Test Links

PHP Version 7.4 :      https://localhost/mdr/Testing/MyObject/TestMyObject.php
PHP Version 7.4 :      https://recDivers.com/Testing/MyObject/TestMyObject.php
PHP Version 8.1 :      https://visablepixels.com/mdr/Testing/MyObject/TestMyObject.php