Jump to content

method using $this as default parameter


fatmuemoo

Recommended Posts

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? :confused:

 

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

$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;
    }
}
?>

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;
    }

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

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.