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
https://forums.phpfreaks.com/topic/58664-setretreive-class-functions/
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.

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.