Skip to content
qnnp

PHP 类继承时的内存空间问题

发布于: | 没有评论 | 分类:

具体影响见代码:

PHP
<?php

abstract class test {
	protected static string $test;

	public static function load( $test ): void {
		$ref  = new ReflectionClass( static::class );
		$prop = $ref->getProperty( 'test' );
		echo 'Calling ' . $ref->getMethod( 'load' )->getDeclaringClass()->getShortName() . '::load() via ' . $ref->getName() . PHP_EOL;
		echo 'Current class is ' . $ref->getShortName() . PHP_EOL;
		echo 'Current property belongs to ' . $prop->getDeclaringClass()->getShortName() . PHP_EOL;
		static::$test = $test;
	}

	public static function get(): void {
		$ref = new ReflectionClass( static::class );
		echo 'Current class is ' . $ref->getShortName() . PHP_EOL;
		echo 'Calling ' . $ref->getMethod( 'get' )->getDeclaringClass()->getShortName() . '::get() via ' . $ref->getName() . PHP_EOL;
		echo 'Current property belongs to ' . $ref->getProperty( 'test' )->getDeclaringClass()->getShortName() . PHP_EOL;
		echo 'Property value is ' . static::$test . PHP_EOL;
	}
}

class a extends test {

	public static function load( $test ): void {
		parent::load( $test );
	}
}

class b extends test {

	public static function load( $test ): void {
		parent::load( $test );
	}
}

class c extends test {
	protected static string $test;

	public static function load( $test ): void {
		parent::load( $test );
	}
}

a::load( 'a' );
b::load( 'b' );
c::load( 'c' );
echo '---' . PHP_EOL;
a::get();
echo '---' . PHP_EOL;
c::get();

// Result:
//	Calling a::load() via a
//	Current class is a
//	Current property belongs to test
//	Calling b::load() via b
//	Current class is b
//	Current property belongs to test
//	Calling c::load() via c
//	Current class is c
//	Current property belongs to c
//	---
//	Current class is a
//	Calling test::get() via a
//	Current property belongs to test
//	Property value is b
//	---
//	Current class is c
//	Calling test::get() via c
//	Current property belongs to c
//	Property value is c

标签:

0 0 投票数
文章评分
订阅评论
提醒
guest
0 评论
内联反馈
查看所有评论

0
希望看到您的想法,请您发表评论x