PHP compatibility - markhowellsmead/helpers GitHub Wiki

Updates to PHP 8.3

The following changes need to be made on older Say Hello projects which use the singleton approach for class loading.

Type matching

Ensure that all class variables are correctly type-matched. e.g. private static ?Theme $instance = null; or public string $name = '';.

Dynamic property creation

Dynamic property creation on PHP classes is deprecated. The dynamically-loaded classes need to be assigned to a container attribute in the main Theme class: private stdClass $containers;.

Getter and setter methods

/**
 * Magic method for setting dynamic properties.
 */
public function __set(string $name, mixed $value): void
{
	$this->containers->{$name} = $value;
}

/**
 * Magic method for getting dynamic properties.
 */
public function __get(string $name): mixed
{
	return $this->containers->{$name} ?? null;
}

Load and initialise classes

/**
 * Loads and initializes the provided classes.
 *
 * @param $classes
 */
private function loadClasses(array $classes): void
{

	$instance = sht_theme(); // Get the singleton instance once.

	foreach ($classes as $class) {
		$class_parts = explode('\\', $class);
		$class_short = end($class_parts);
		$class_set   = $class_parts[count($class_parts) - 2];

		if (!isset($instance->{$class_set}) || !is_object($instance->{$class_set})) {
			$instance->{$class_set} = new stdClass();
		}

		if (property_exists($instance->{$class_set}, $class_short)) {
			error_log(sprintf(
				_x(
					'Ein Problem ist geschehen im Theme. Nur eine PHP-Klasse namens «%1$s» darf dem Theme-Objekt «%2$s» zugewiesen werden.',
					'Duplicate PHP class assignment in Theme',
					'sht'
				),
				$class_short,
				$class_set
			));
		} else {
			$instance->{$class_set}->{$class_short} = new $class();
			if (method_exists($instance->{$class_set}->{$class_short}, 'run')) {
				$instance->{$class_set}->{$class_short}->run();
			}
		}
	}
}