-
get and set methods
Hello every one!
does any one have nay idea that is there any get and set method in php like we have in following C#
public int ProductID
{
get
{
return intProductID;
}
set
{
intProductID=value;
}
}
so does any one have knowldege how to make a class where i write
my code in php like above manner
Hope any one would reply me
-
Re: get and set methods
The usual way is to use two methods: getProductID and setProductID. This avoids confusion as it is obvious that a method is being called rather than a field being read/set directly.
If there is nothing special that should be done when assigning or reading a property then you should just make the field public.
You can also use the magic methods __get and __set. These are not quite as nice as the property syntax in .NET as you have to place all of the logic for every property into the two methods. When using this approach it is simplest to store all of the properties in a private array.
PHP Code:
class PropertyExample
{
private $_properties = array();
public function __get($prop)
{
return $this->_properties[$prop];
}
public function __set($prop, $val)
{
$this->_properties[$prop] = $val;
}
}
-
Re: get and set methods
and how to make object of this class and use these proeprties(get and set)
-
Re: get and set methods
Just like C#
PHP Code:
$myobj = new MyClass();
$myobj->myprop = somevalue;
echo $myobj->myprop;