CLASS web

PHP

this in class

Using this

You should also know this before you can test the restrictor. ㅜㅜ
this is I'd like to use in my classes. Used to access a property or method declared in a class.

How to use properties using this

this->propertyname;

How to use a method using this

this-> method name();

Don't know what I'm talking about yet? You can use it like this:
Here is an example of using a property in a method:

<?php
    class Car
    {
        public $wheels = 4;

        public function checkWheelsCount()
        {
            return "This car has {$this->wheels} wheels.";
        }
    }

    $honda = new Car;
    echo $honda->checkWheelsCount();
?>

I'll check the results right below.







Result

In other words, you should not use $wheels in a class like this: $this->wheels.
The following is an example of calling another method from a method of a class.

<?php
    class Car
    {
        public $wheels = 4;

        public function checkWheelsCount()
        {
            return $this->wheels;
        }

        public function outputWheelsCount()
        {
            return "This car has {$this->checkWheelsCount()} wheels.";
        }
    }

    $honda = new Car;
    echo $honda->outputWheelsCount();
?>

I'll check the results right below.







Result

The code above functions that the method checkWheelsCount() returns the wheels property and called checkWheelsCount() in the outputWheelsCount() method.





ALL COMMENTS 0

Sort by

PinkCoding

PinkCoding

X

PinkCoding

Web Scratch Pad

X

loading

            
            
        

Back to the course