Aadil Hafesji
Aadil Hafesji

Reputation: 397

PHP Can you use the same property in different classes

I am pretty new to oop php and I just wanted to know if you could use the same properties within multiple classes. For example:

<?php
    class bank {
        public $holders_firstName = "Aadil";
        public $holders_lastName = "Hafesji";
        public $holders_currentNumber = 456789111;
        public $holders_aaCode = "20-55-66";
        public $holders_b = "£8";
    }

    class check {
        $obj = new check;

        echo $obj->holders_firstName;
    }

    class save {
        //
    }
?>

Could I use all those public properties that is in the first class (bank) within the second class (check) or even in the third class (save) using that code?

Upvotes: 0

Views: 731

Answers (2)

Nathan F.
Nathan F.

Reputation: 3489

If you define them again in the other classes, then technically yes you could. But they are separate objects, so they wouldn't store the same values.

It's like having a car, a ball and a book. They all have the property "color", but the values are different for each, and changing any one of them will not effect the others.

class Car {
    public $color;
}

class Ball {
    public $color;
}

class Book {
    public $color;
}

$car = new Car;
$car->color = "red";

$ball = new Ball;
$ball->color = "blue";

// The color for the car and the ball are still red and blue after this.
$book = new Book;
$book->color = "green";

However, I would also like to add that you seem to have a misconception of how OOP works in general. These "classes" aren't objects themselves, but instead are to Objects what Blueprints are to a House.

When you create a class, it just lays out a map of what an object (or instance) of this class will look like.

When you call new MyClass, it will actually take that blueprint for the class and create a new object based off of it.

So, in that sense, if you have a class called Car, you could create multiple Cars. Each with their own Speed, Color, Etc.

class Car {
    public $speed;
    public $color;
}

$corvette = new Car;
$corvette->speed = 500;
$corvette->color = 'red';

$civic = new Car;
$civic->speed = 20;
$civic->color = 'rust';

Each of these cars now exists independent of each other, but they were created using the same Class (or blueprint so to speak).


If what you're trying to do is create a class that shares the same properties, so that you can create other classes that have those properties you can use inheritance:

class Car {
    public $speed;
}

class ColoredCar extends Car {
    public $color;
}

$corvette = new ColoredCar;
$corvette->speed = 100;
$corvette->color = 'red';

Upvotes: 1

Gias
Gias

Reputation: 76

you have to use oop inheritance . you can extend one class within other and use its funtionality. eg.

class save extends check {}

Upvotes: 1

Related Questions