Tharos
Tharos

Reputation: 31

Creating PHP CLASS for USERS

So, here is my problem and I would very much appreciate any help. I have this assignment: Create class User with this properties: id, first_name, last_name, age. Class must have: 1) Constructor, 2)Method that returns fname and lname, and 3) Method that returns boolean if user is underaged or not. Then, create an Object as instance for created class, and through object call both methods and show result on page.

This is what I created so far, but I think I am not going in the right direciton:

<?php

class UsersClass {

    public $user_id;
    public $first_name;
    public $last_name;
    public $age;

    public function __construct () {
        $this->user_id = $user_id;
        $this->first_name = $first_name;
        $this->last_name = $last_name;
    }

    public function notUnderaged ($age) {
        $this->age = $age;
        if($age<18) {
            $ageOK = false;
        }else{
            $ageOK = true;
        }
        echo $ageOK;
    }

    public function dataOutput ($first_name, $last_name) {

        echo "First name: " . $this->first_name . "<br/>Last name: " . $this->last_name;

    }

}

$user = new UsersClass;
$user->dataOutput($first_name, $last_name);
$user->user_id = 0001;
$user->first_name = "Vladimir";
$user->last_name = "Bozic";
$user->age = 17;

?>

Thanks ahead!

Upvotes: 0

Views: 4191

Answers (1)

Aseem Upadhyay
Aseem Upadhyay

Reputation: 4537

Yes there are some issues.

  1. Your constructor should be parameterised

    public function __construct ($user_id, $first_name,$last_name) { $this->user_id = $user_id; $this->first_name = $first_name; $this->last_name = $last_name; }

  2. Method that returns first name and last name. You should have methods that return last name and first name. public function getLastName() { return $this->last_name;}. Similarly for first name.

  3. notUnderaged method should return $ageOk and not echo $ageOk

  4. Lastly, all your variables should be private. Since your question doesn't state them to be public.

  5. Your method dataOutput() isn't required.

So, you'll be calling it like

$user = new UserClass(001,'Vladmir','Bozic');
$lastName = $user->getLastName();
$firstName = $user->getFirstName();

and so on..

P.S: Tips - It's preferred class methods have getter and setter methods. It provides transparency and visibility of your class implementation. Any operation regarding fetching a value from a variable or performing some operation should be done either via the getter/setter methods or methods derived from getter and setter methods.

Upvotes: 1

Related Questions