I am new to php oop, I have a some idea re Classes but I still don't get around how to use its properties and methods in a created Object. I need to understand if the code reported below is correct, and if not what I do wrong.
I am assuming that I have a Class that can do anything for me. Let's call it Class myClass {....}
Now I create an object from it and try to work with its methods and properties like this:-
$myObject = new myClass;
$myObject->checkSpeedLight(); // method for checking the speed
if($this->lightSpeed > 10000) echo (“slow down!”); // property defined with a value of 10000
if($this->lightSpeed =< 10000) echo (“Speed up!);
$myObject->keepLightingUp();
$myObject->sleep();
echo ("ligth up");
It has no sense I know, it is just an example. What I need to understand is if the way is written is correct; Any help appreciated.
$this
is out of context, it can only be used from within the class definition (inside of internal methods etc).Outside of the function, we use
$myObject->lightspeed
;Also, I'm assuming that you are setting the
lightspeed
property with thecheckLightSpeed()
method.EDIT!
Additionally, it's considered good practice to have a getter and setter methods. The point is to not access your properties directly, but through an abstraction layer method.
This way you have more control over what, how and when you view your property (for instance, you can require a database connection in order to view it, or restrict access).
Also note that the property itself is declared private, so direct access from outside the class's guts is restricted.
For instance, this is my SpeedOfLight class made in PHP:
(I didn't know what
keepLightSpeed()
orsleep()
were so I omitted them, but this is the key part).Other than that, you're good.