How to set the default argument of a method for a class member

I have this inside the php class:

$this->ID = $user_id;

public function getUserFiles($id = $this->ID) { } // error here

But apparently I am not allowed to use the property in this way. So, how can I say that the default value of the method argument should be the value of the ID property?

There should be a better way:

$this->ID = $user_id;

public function getUserFiles($id = '') {
    $id = ($id == '') ? $this->ID : $id;
}
+3
source share
2 answers

I usually use null in this situation:

public function getUserFiles($id = null)
{
    if ($id === null) {
        $id = $this->id;
    }
    // ...
}
+10
source

Assuming (for some reason and design), in the method, in the case of the default parameter, we just want to use the attribute instead, than I would also do it like Alex:

public function methodABC($param = NULL) {
    if ( $param === NULL ) {
        $param = $this->attributeUVW;
    }
    ...$param...
    }

... and here is the full code for the game (my 2 cents):

<?php

    class MyClass
    {
    public $attributeUVW;
    function __construct() {
            $this->attributeUVW = 1234;
        }
    public function methodABC($param = NULL) {
        if ( $param === NULL ) {
            $param = $this->attributeUVW;
        }
        echo '<p>"'.$param.'"</p>'."\n";
        }
    }

    echo '<html>'."\n";
    echo '<body>'."\n";
    echo '<h1>class X</h1>'."\n";

    $x = new MyClass;
    $x->methodABC();
    $x->methodABC(5678);

    echo '</body>'."\n";
    echo '</html>'."\n";

?>

... prints:

<html>
<body>
<h1>class X</h1>
<p>"1234"</p>
<p>"5678"</p>
</body>
</html>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1791277/


All Articles