Objects in PHP syntax – Hello World script

Here are some examples.

1
2
3
4
5
6
7
<?php
         class Cat
            {
                public $isAlive = true;
                public $numLegs = 4;
            }
        ?>

This is a simple class. It is named “Cat”. The class should hold the main variables that are passed when calling the object.

2
3
4
5
6
7
8
9
10
11
12
13
 <?php
         class Cat
            {
                public $isAlive = true;
                public $numLegs = 4;
 
                public function __construct($name)
                    {
                        $this->name = $name;   
                    }
            }
        ?>

This one has a public function __construct which will allow the user to add values with “new Cat”.

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        <?php
         class Cat
            {
                public $isAlive = true;
                public $numLegs = 4;
 
                public function __construct($name)
                    {
                        $this->name = $name;   
                    }
                public function meow()
                    {
                        return "Meow meow";   
                    }
            }
 
        $cat1 = new Cat("CodeCat");
        echo $cat1->meow();
        ?>

This example adds a new function that will actually do something: return “Meow, meow”. You call it with echo $cat1->meow();.

ADD A COMMENT: