php oop how to work with properties and methods fo

2020-05-08 01:26发布

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.

标签: php oop
1条回答
该账号已被封号
2楼-- · 2020-05-08 02:22

$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 the checkLightSpeed() 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.

class MyClass {
    private $property = "Hello World!";

    public function getProperty() {
        return $this->property;
    }
}

$obj = new MyClass();
$obj->getProperty();

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:

<?php

    /**
     * @class                  SpeedOfLight
     *
     * @property $speedOfLight private
     *
     */
    class SpeedOfLight {

        private $speedOfLight;

        public function checkSpeedOfLight() {
            $this->speedOfLight = 300000000;
        }

        public function getSpeedOfLight() {
            return $this->speedOfLight;
        }

    }

    #Begin testing!
    $obj = new SpeedOfLight();
    $obj->checkSpeedOfLight();

    if ($obj->getSpeedOfLight() <= 100000000) {
        echo "Speed up!";
    }
    elseif ($obj->getSpeedOfLight() >= 350000000) {
        echo "Slow down!";
    }
    else {
        echo "Just right!";
    }

(I didn't know what keepLightSpeed() or sleep() were so I omitted them, but this is the key part).


Other than that, you're good.

查看更多
登录 后发表回答