蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 PHP 8.4 类生命周期、继承重写、访问控制、接口抽象类与 static/final 实验

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-oop.php
explore-oop.php372 行
<?php
declare(strict_types=1);

$cases = [];

// Case 1: class, object instantiation, $this, __construct, __destruct lifecycle
class Site
{
    public string $url;
    public string $title;

    public function __construct(string $url = '', string $title = '')
    {
        $this->url = $url;
        $this->title = $title;
    }

    public function setUrl(string $par): void
    {
        $this->url = $par;
    }

    public function getUrl(): string
    {
        return $this->url;
    }

    public function setTitle(string $par): void
    {
        $this->title = $par;
    }

    public function getTitle(): string
    {
        return $this->title;
    }
}

$lifecycleLog = [];
class TrackedResource
{
    private string $name;
    /** @var array<int, string> */
    private $logRef;

    /** @param array<int, string> $log */
    public function __construct(string $name, array &$log)
    {
        $this->name = $name;
        $this->logRef = &$log;
        $this->logRef[] = 'construct:' . $this->name;
    }

    public function __destruct()
    {
        $this->logRef[] = 'destruct:' . $this->name;
    }
}

$s1 = new Site();
$s1->setTitle('蓝色天空');
$s1->setUrl('mbsky.local');
$s2 = new Site('docs.example.org', '文档中心');

$res = new TrackedResource('HandleA', $lifecycleLog);
unset($res); // trigger __destruct deterministically

$c1Actual = [
    's1_title' => $s1->getTitle(),
    's1_url' => $s1->getUrl(),
    's2_pair' => $s2->getTitle() . '@' . $s2->getUrl(),
    'lifecycle' => $lifecycleLog,
];
$c1Expected = [
    's1_title' => '蓝色天空',
    's1_url' => 'mbsky.local',
    's2_pair' => '文档中心@docs.example.org',
    'lifecycle' => ['construct:HandleA', 'destruct:HandleA'],
];
$cases[] = [
    'name' => 'class_objects_construct_destruct',
    'passed' => $c1Actual === $c1Expected,
    'expected' => $c1Expected,
    'actual' => $c1Actual,
];

// Case 2: inheritance (extends), method overriding, and parent::__construct()
class ChildSite extends Site
{
    public string $category = '';

    public function setCate(string $cate): void
    {
        $this->category = $cate;
    }

    public function getTitle(): string
    {
        return '[' . $this->category . '] ' . parent::getTitle();
    }
}

$ctorLog = [];
class BaseNode
{
    public function __construct(array &$log)
    {
        $log[] = 'BaseNode::__construct';
    }
}

class SubNode extends BaseNode
{
    public function __construct(array &$log)
    {
        parent::__construct($log);
        $log[] = 'SubNode::__construct';
    }
}

class InheritNode extends BaseNode
{
    // inherits BaseNode::__construct automatically
}

$child = new ChildSite('code.example.org', '代码库');
$child->setCate('PHP');
new BaseNode($ctorLog);
new SubNode($ctorLog);
new InheritNode($ctorLog);

$c2Actual = [
    'overridden_title' => $child->getTitle(),
    'inherited_url' => $child->getUrl(),
    'ctor_log' => $ctorLog,
];
$c2Expected = [
    'overridden_title' => '[PHP] 代码库',
    'inherited_url' => 'code.example.org',
    'ctor_log' => [
        'BaseNode::__construct',
        'BaseNode::__construct',
        'SubNode::__construct',
        'BaseNode::__construct',
    ],
];
$cases[] = [
    'name' => 'inheritance_override_and_parent_construct',
    'passed' => $c2Actual === $c2Expected,
    'expected' => $c2Expected,
    'actual' => $c2Actual,
];

// Case 3: visibility (public/protected/private) + private binding vs public override
class VisibilityBase
{
    public string $pub = 'Public';
    protected string $prot = 'Protected';
    private string $priv = 'Private';

    public function dumpOwn(): string
    {
        return "{$this->pub}|{$this->prot}|{$this->priv}";
    }

    public function testDispatch(): array
    {
        return [$this->testPrivate(), $this->testPublic()];
    }

    public function testPublic(): string
    {
        return 'Base::testPublic';
    }

    private function testPrivate(): string
    {
        return 'Base::testPrivate';
    }
}

class VisibilityChild extends VisibilityBase
{
    protected string $prot = 'Protected2';

    public function dumpChild(): string
    {
        return "{$this->pub}|{$this->prot}";
    }

    public function testPublic(): string
    {
        return 'Child::testPublic';
    }

    private function testPrivate(): string
    {
        return 'Child::testPrivate';
    }
}

$vb = new VisibilityBase();
$vc = new VisibilityChild();
$protBlocked = false;
try {
    $_ = $vb->prot;
} catch (\Error $e) {
    $protBlocked = true;
}
$privBlocked = false;
try {
    $_ = $vb->priv;
} catch (\Error $e) {
    $privBlocked = true;
}

$c3Actual = [
    'public_direct' => $vb->pub,
    'base_internal' => $vb->dumpOwn(),
    'child_override_prot' => $vc->dumpChild(),
    'external_protected_throws' => $protBlocked,
    'external_private_throws' => $privBlocked,
    'dispatch_private_vs_public' => $vc->testDispatch(),
];
$c3Expected = [
    'public_direct' => 'Public',
    'base_internal' => 'Public|Protected|Private',
    'child_override_prot' => 'Public|Protected2',
    'external_protected_throws' => true,
    'external_private_throws' => true,
    'dispatch_private_vs_public' => ['Base::testPrivate', 'Child::testPublic'],
];
$cases[] = [
    'name' => 'visibility_public_protected_private',
    'passed' => $c3Actual === $c3Expected,
    'expected' => $c3Expected,
    'actual' => $c3Actual,
];

// Case 4: interface, abstract class, optional parameter widening, polymorphism
interface TemplateEngine
{
    public function setVariable(string $name, string $val): void;
    public function getHtml(string $template): string;
}

class SimpleTemplate implements TemplateEngine
{
    /** @var array<string, string> */
    private array $vars = [];

    public function setVariable(string $name, string $val): void
    {
        $this->vars[$name] = $val;
    }

    public function getHtml(string $template): string
    {
        foreach ($this->vars as $name => $value) {
            $template = str_replace('{' . $name . '}', $value, $template);
        }
        return $template;
    }
}

abstract class AbstractFormatter
{
    abstract protected function getTag(): string;
    abstract protected function prefixName(string $name): string;

    public function render(string $name): string
    {
        return $this->getTag() . ':' . $this->prefixName($name);
    }
}

class FormalFormatter extends AbstractFormatter
{
    protected function getTag(): string
    {
        return 'Formal';
    }

    // Widened visibility (protected -> public) + extra optional parameter
    public function prefixName(string $name, string $separator = '.'): string
    {
        $prefix = match ($name) {
            'Pacman' => 'Mr',
            'Pacwoman' => 'Mrs',
            default => '',
        };
        return $prefix !== '' ? "{$prefix}{$separator} {$name}" : $name;
    }
}

$tpl = new SimpleTemplate();
$tpl->setVariable('user', 'PHP8');
$fmt = new FormalFormatter();

$c4Actual = [
    'template_output' => $tpl->getHtml('Hello, {user}!'),
    'abstract_render_pacman' => $fmt->render('Pacman'),
    'abstract_render_pacwoman' => $fmt->render('Pacwoman'),
    'optional_sep_override' => $fmt->prefixName('Pacman', ':'),
    'abstract_not_instantiable' => (new \ReflectionClass(AbstractFormatter::class))->isAbstract(),
];
$c4Expected = [
    'template_output' => 'Hello, PHP8!',
    'abstract_render_pacman' => 'Formal:Mr. Pacman',
    'abstract_render_pacwoman' => 'Formal:Mrs. Pacwoman',
    'optional_sep_override' => 'Mr: Pacman',
    'abstract_not_instantiable' => true,
];
$cases[] = [
    'name' => 'interface_abstract_and_polymorphism',
    'passed' => $c4Actual === $c4Expected,
    'expected' => $c4Expected,
    'actual' => $c4Actual,
];

// Case 5: class const, static property/method, and final class/method guards
class StaticAndConst
{
    public const LABEL = '常量值';
    public static string $shared = 'foo';

    public function readSelf(): array
    {
        return [self::LABEL, self::$shared];
    }
}

final class SealedService
{
    final public function lockedAction(): string
    {
        return 'locked';
    }
}

$clsName = StaticAndConst::class;
$scObj = new StaticAndConst();
$refSealed = new \ReflectionClass(SealedService::class);
$refMethod = $refSealed->getMethod('lockedAction');

$c5Actual = [
    'const_via_class' => StaticAndConst::LABEL,
    'const_via_var' => $clsName::LABEL,
    'const_via_obj' => $scObj::LABEL,
    'static_direct' => StaticAndConst::$shared,
    'self_access' => $scObj->readSelf(),
    'final_class' => $refSealed->isFinal(),
    'final_method' => $refMethod->isFinal(),
];
$c5Expected = [
    'const_via_class' => '常量值',
    'const_via_var' => '常量值',
    'const_via_obj' => '常量值',
    'static_direct' => 'foo',
    'self_access' => ['常量值', 'foo'],
    'final_class' => true,
    'final_method' => true,
];
$cases[] = [
    'name' => 'const_static_and_final_guards',
    'passed' => $c5Actual === $c5Expected,
    'expected' => $c5Expected,
    'actual' => $c5Actual,
];

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-oop-lab/explore-oop.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-oop.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1277.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习