php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #80039 Illegal string offset and Cannot create references to/from string offsets
Submitted: 2020-08-31 09:03 UTC Modified: 2020-08-31 09:43 UTC
From: miloslav dot hula at gmail dot com Assigned: nikic (profile)
Status: Closed Package: *General Issues
PHP Version: 7.4.9 OS:
Private report: No CVE-ID: None
 [2020-08-31 09:03 UTC] miloslav dot hula at gmail dot com
Description:
------------
This is probably related to https://bugs.php.net/bug.php?id=80037

The test scripts emits warning and fatal error when creating a reference to static variable.

The test script is reduced to show the error. In production code, there is a relation between referenced value in fromArray() and $prop = &$cache ...

For example, when I call:

A::fromArray(['a' => 'foo']);

the error is emmited, the exception handler executed and

$prop = &$cache[$class][$name];

normally pass. But, the $prop contains 'foo' string.

Test script:
---------------
<?php

final class A
{
	public string $a;

	public static function fromArray(array $props): self
	{
		$me = new static;
		foreach ($props as $k => &$v) {
			$me->{$k} = &$v;
		}
		return $me;
	}

	public function __get($name)
	{
		throw new \LogicException("Property '$name' is not defined.");
	}
}

class ObjectHelpers
{
	public static function hasProperty(string $class, string $name)
	{
		static $cache = [];
		$prop = &$cache[$class][$name];  # <-- emits error
	}
}

set_exception_handler(function ($e) {
	ObjectHelpers::hasProperty(A::class, 'a');
});

A::fromArray(['a' => 'foo']);

Expected result:
----------------
(no error)

Actual result:
--------------
Warning: Illegal string offset 'a' in bug.php on line 27

Fatal error:  Uncaught Error: Cannot create references to/from string offsets in bug.php:27
Stack trace:
#0 bug.php(32): ObjectHelpers::hasProperty('A', 'a')
#1 [internal function]: {closure}(Object(Error))
#2 {main}
  thrown in bug.php on line 27


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2020-08-31 09:12 UTC] nikic@php.net
Hm, I can't reproduce this on current 7.4/master HEAD, just get empty output. Possibly this has been fixed recently?
 [2020-08-31 09:19 UTC] miloslav dot hula at gmail dot com
And when you

$prop = &$cache[$class][$name];
var_dump($prop);

the $prop is NULL?
 [2020-08-31 09:43 UTC] nikic@php.net
-Status: Open +Status: Closed -Assigned To: +Assigned To: nikic
 [2020-08-31 09:48 UTC] miloslav dot hula at gmail dot com
Thank you. But I think that test may fail in future. IMHO the exception should not be thrown at all. I reported this as a consequence of https://bugs.php.net/bug.php?id=80037
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sat Dec 21 14:01:32 2024 UTC