Jump to content

Set/Retreive class functions?


Koobazaur

Recommended Posts

Hi,

 

I have a class that has a bool value like:

 

$bDoSomething.

 

I want to have functions to set/get that variable but I want to use the same function name for both. I tried the c way:

 

public function something()
{
return $bDoSomething;
}
public function something($bToSet)
{
return $bDoSomething = $bToSet;
}

 

But I get an error that the something function is already declared. I tried this:

public function something($bToSet)
{
if(isset($bToSet)
$bDoSomething = $bToSet;
return $bDoSomething;
}

 

And while it works, I get a warning whenever calling my function and not passing anything to it.

 

What's the proper way of achieving waht I want here?

Link to comment
Share on other sites

Overloading works a bit different in PHP, you can do something like this:

<?php
class Test
{
private $bDoSomething;

public function __call($name, $arguments=array())
{
	if($name=='something')
	{
		if(count($arguments) == 0) // something()
		{
			return $this->bDoSomething;
		}
		else if(count($arguments) == 1) // something($bToSet)
		{
			$this->bDoSomething = $arguments[0];
			return $this->bDoSomething;
		}
		else {
			trigger_error("Invalid argument count", E_USER_ERROR);
		}
	}
}
}

$test = new Test();
$test->something("test");
echo $test->something(); // output: test
?>

 

You could also choose to do it in another way (like you attempted):

<?php
class Test
{
private $bDoSomething;

public function something($bToSet=null)
{
	if(!empty($bToSet))
	{
		$this->bDoSomething = $bToSet;
	}

	return $this->bDoSomething;
}
}

$test = new Test();
$test->something("test");
echo $test->something(); // output: test
?>

 

Note that overloading is for PHP5 only.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.