fatmuemoo Posted August 1, 2009 Share Posted August 1, 2009 Hi Everyone, This is my first post and I am relatively new to OOP so please bare with me. This is the code: <?php Class SomeClass { public function f1() { $this->v1 = "something"; $this->v2 = "somethingelse"; f2(); } public function f2($parameter1=$this->v1, $parameter2=$this-v2) { return true; } } ?> could someone explain why I get a parse error on line 10, where public function f2($parameter1=$this->v1, $parameter2=$this-v2) is declared? Basically, I want to be able to have a method that has the default parameters of $this->v1 and $this-v2, but I want to be able to call that function using different value as well. Thanks! Link to comment https://forums.phpfreaks.com/topic/168416-method-using-this-as-default-parameter/ Share on other sites More sharing options...
gevans Posted August 1, 2009 Share Posted August 1, 2009 $parameter2=$this-v2 A little arrow missing! $parameter2=$this->v2 Also you should declare those variables outside of the methods... <?php Class SomeClass { private var $v1; private var $v2; public function f1() { $this->v1 = "something"; $this->v2 = "somethingelse"; f2(); } public function f2($parameter1=$this->v1, $parameter2=$this->v2) { return true; } } ?> Link to comment https://forums.phpfreaks.com/topic/168416-method-using-this-as-default-parameter/#findComment-888388 Share on other sites More sharing options...
Daniel0 Posted August 1, 2009 Share Posted August 1, 2009 You can only assign a constant as default argument value. You can, however, do something like this: public function f2($parameter1 = null) { if ($parameter1 === null) { $parameter1 = $this->v1; } return true; } Link to comment https://forums.phpfreaks.com/topic/168416-method-using-this-as-default-parameter/#findComment-888392 Share on other sites More sharing options...
gevans Posted August 1, 2009 Share Posted August 1, 2009 You can only assign a constant as default argument value. Really!? I didn't know that. I should a bit better. Link to comment https://forums.phpfreaks.com/topic/168416-method-using-this-as-default-parameter/#findComment-888396 Share on other sites More sharing options...
fatmuemoo Posted August 1, 2009 Author Share Posted August 1, 2009 You can only assign a constant as default argument value. You can, however, do something like this: public function f2($parameter1 = null) { if ($parameter1 === null) { $parameter1 = $this->v1; } return true; } That was the problem. Also , f2(); is invalid. It must be $this->f2(); Thanks, everyone, I can tell I'm gong to like here on phpfreaks.com Link to comment https://forums.phpfreaks.com/topic/168416-method-using-this-as-default-parameter/#findComment-888399 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.