Hey all. Looking beyond the purpose of the following two OOP examples, which is considered common or the correct structure? Or is it simply preference?
Example 1:
class names
{
private $first_name;
public function setUpperCase($first_name)
{
$this->first_name = ucfirst($first_name);
}
public function viewUpperCase()
{
echo $this->first_name;
}
}
$names = new names();
$names->setUpperCase("jimbo");
$names->viewUpperCase();
Example 2:
class names
{
public function setUpperCase($first_name)
{
$upper_first_name = ucfirst($first_name);
return $upper_first_name;
}
public function viewUpperCase($upper_first_name)
{
echo $upper_first_name;
}
}
$names = new names();
$uppercase = $names->setUpperCase("jimbo");
$names->viewUpperCase($uppercase);
The first example sets the variable within the class structure. The second example sets the variable as a method argument. Both do exactly the same thing. But which is “proper”?
Thanks all. Cheers!
Im going to go out on a limb and say the first example would be the “right” method as an object by definition is defined by properties.
It almost seems like you have the beginnings of a user class that has a name that can have certain modifications applied, such as your uppercase method.
The second example looks like it could just be a utility and I wouldnt describe it as a true object as it doesnt have any properties.