Hi there.
The thing is I am really bad at classes in php and I have an assignment:
“Create user class which contains user data, like: id, e-mail, password, name…
The class should also have a method to show all the user data.”
Is someone could help me or point me in the right direction please.
Thank you in advance.
The class name doesn’t reflect what it “is”. Yes it’s info, but that’s pretty much everything we’re doing when programming. “User”, “Person” or similar would make more sense.
The getters/setters are kinda redundant when the class properties are public (you can just do $instance->foo = ‘bar’). Though I’d advice to use the methods and change the properties to protected or private
A nice “trick” is to return $this on the setters. that way you can do the following - which looks a lot better and is usually preferred.
I was giving a simple example of a class. Generally, a class’s properties should be only as visible as they need to be, hence private, protected, public. Classes should be a blackbox. You send info to them, don’t know how they work and don’t care, just that you get out what you expect.
What book are you following? Read through it again and see what you glean.
[php]class Vehicle
{
private $_make;
private $_model;
private $_year;
public function __construct( $make, $model, $year ) {
$this->_make = $make;
$this->_model = $model;
$this->_year = (int) $year;
}
public function __toString(){
return “This instance of Car is for a {$this->_year} {$this->_make} {$this->_model}.”;
}
}
$sport = new Vehicle( ‘Chevrolet’, ‘Corvette’, 2015);
$suv = new Vehicle(‘Jeep’, ‘Wrangler’, 1974);