在 php if 参数中切换可见性

Switch visibility in php if parameter

我想知道是否可以在 PHP 中切换可见性。让我演示一下:

class One {

     function __construct($id){

       if(is_numeric($id)){

          //Test function becomes public instead of private.

       }

     }


    private function test(){

       //This is a private function but if $id is numeric this is a public function

    }

}

这有可能吗?

它可以被伪造到一定程度 magic methods:

<?php

class One {
    private $test_is_public = false;

    function __construct($id){
        if(is_numeric($id)){
            $this->test_is_public = true;
        }
    }

    private function test(){
        echo "test() was called\n";
    }

    public function __call($name, $arguments){
        if( $name=='test' && $this->test_is_public ){
            return $this->test();
        }else{
            throw new LogicException("Method $name() does not exist or is not public\n");
        }
    }
}

echo "Test should be public:\n";
$numeric = new One('123e20');
$numeric->test();

echo "Test should be private:\n";
$non_numeric = new One('foo');
$non_numeric->test();

我还没想过副作用。可能,它仅作为概念证明有用。

我会使用一个抽象 class 和两个实现 classes:一个用于数字,一个用于非数字:

abstract class One {

    static function generate($id) {
        return is_numeric($id) ? new OneNumeric($id) : new OneNonNumeric($id);
    }

    private function __construct($id) {
        $this->id = $id;
    }

}

class OneNumeric extends One {

    private function test() {

    }

}

class OneNonNumeric extends One {

    public function test() {

    }

}

$numeric = One::generate(5);
$non_numeric = One::generate('not a number');

$non_numeric->test(); //works
$numeric->test(); //fatal error