Skip to content

Erroneous call of magic functions on class variables, erroneous assignment of data to a variable #11851

@AlexeyZamorov

Description

@AlexeyZamorov

Description

The following code:

<?php
class TClass
{
	public function something() : array
	{
		unset(self::$Cache->Content);

		return [];
	}
	public static TCache $Cache;
}

TClass::$Cache = new TCache();

class TCache
{
	public function __destruct()
	{
		if(isset($this->Hash, $this->Content)) {}
	}

	public function &__get(string $name)
	{
		if(!isset($this->Content))
		{
			$this->Content = [];
			$this->Hash = false;
		}

		return $this->Content;
	}

	public function __set(string $name, string|array|false $value) : void
	{
		$this->Content = $value;

		// this code is failing
		$this->Hash ??= false;

		//this code works correctly
		//if(!isset($this->Hash)) { $this->Hash = false; }
	}

	public function __isset(string $name) : bool
	{
		if(!isset($this->Content))
		{
			$this->__get($name);
		}

		return isset($this->Content);
	}

	public function __unset(string $name) : void
	{
		unset($this->Content, $this->Hash);
	}

	protected string|array|false $Content;
	protected string|false $Hash;
}

(new TClass())->something();

Resulted in this output:

PHP Fatal error:  Uncaught TypeError: Cannot assign array to property TCache::$Hash of type string|false in test.php:38
Stack trace:
#0 test.php(26): TCache->__set('Content', Array)
#1 test.php(48): TCache->__get('Content')
#2 test.php(46): TCache->__isset('Content')
#3 test.php(19): TCache->__isset('Hash')
#4 [internal function]: TCache->__destruct()
#5 {main}
  thrown in test.php on line 38

Process finished with exit code 255

But I expected this output instead:

Process finished with exit code 0

PHP Version

8.1.21

Operating System

FreeBSD 13.2

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions