Thursday, 15 February 2018

How are variables assigned in PHP classes?

Public variables allow you to modify them directly as fields as instead of going through public methods. Add the following lines:


    $cat1 = new Cat( "CodeCat" );
echo $cat1->meow();
$cat1->name = "Another Cat";
echo $cat1->meow();

You will see:


Meow meow. CodeCat
Meow meow. Another Cat

You are able to change the value of $name even after construction.


With a private property:


Change the accessor of $name to private from public, you will get this error:


Fatal error: Cannot access private property Cat::$name

when trying to assign it a value from the $cat1 object.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...