PHP set a function var from false to true from out

2019-09-22 09:22发布

问题:

There is an annoying function inside a class which adds advertisements and I want them removed from outside the class. The function looks like this:

class Ads_Form {
    public function admin_footer( $submit = true, $show_sidebar = true ) {
        if ( $show_sidebar ) {
            $this->admin_sidebar();
        }
    }
}

As you can see there is a variable called $show_sidebar which is set to true by default.

How can I set this var to false from outside the class?

回答1:

When you call this method, if you provide no arguments, it will default to false:

$obj = new Ads_Form();
$obj->admin_footer();
// $show_sidebar gets set to true

Just pass it arguments, which will override the defaults:

$obj = new Ads_Form();
$obj->admin_footer(true, false);
// $show_sidebar gets set to false


回答2:

Difficult to achieve without editing the file itself. Either way you are going to have to edit the class, or every file / function that calls this function.

Rather than remove the class or change the defaults, if you have permission to edit the class file, just comment out the line:

// $this->admin_sidebar();

This will prevent any calls to this function from being overwritten, and it will disable the ads elsewhere.

You can also just change the default value:

admin_footer( $submit = true, $show_sidebar = false )


回答3:

class Ads_Form {
    public $show_sidebar = true;

    public function admin_footer($submit = true, $show_sidebar = null) {
        if(!is_null($show_sidebar)) {
            $this->show_sidebar = (boolean)$show_sidebar;
        }
    }

    if($this->show_sidebar) {
        echo 'test<br>';
    }
}

Test code!

$Ads_Form = new Ads_Form;
echo '------------TEST 1-------------<br>';
$Ads_Form->admin_footer();
$Ads_Form->show_sidebar = false;
echo '------------TEST 2-------------<br>';
$Ads_Form->admin_footer();


标签: php class