0

I have a question close to this:

How to create constructor with optional parameters?

It is clear that we can make optional params like this:

function myFunction($param='hello')

but I want to use it in a class's method with $this->something instead of 'hello', it looks like this:

public function myFunction($param=$this->property)

but I get a:

Parse error: syntax error, unexpected '$this'

Is it possible to get it?

Pek
  • 166
  • 1
  • 15
user2674471
  • 35
  • 2
  • 8

2 Answers2

0

You can do it like this

$Obj = new myclass();
class myclass{

    var $data = 'tested';
    function __construct(){
        $this->testFunction();
    }

    public function testFunction($param = null){
        if( $param == '' || $param == null){
            $param = $this->data;
        }
        echo $param;
    }
}
Munshi Azhar
  • 307
  • 1
  • 8
  • I think putting if($param=== null) would be better than if($param=='' OR $param ==null) because a '' may be a valid value in my case, anyway thank you a lot. – user2674471 Dec 03 '17 at 03:36
0

you need to set to null and check afterward

 class example {
 private $something = "something";
 public function myFunction($a = null) 
 {
    if($a === null) 
       $a = $this->something; 
     // more code goes here
    return $a; 
  }
 }
 $test = new example();
 print $test->myFunction();
 // prints "something"
 print $test->myFunction("hello");
 // prints "hello"