mirror of
https://github.com/restoreddev/phpapprentice.git
synced 2025-08-01 12:30:57 +02:00
Wrote inital content for classes-visibility and tweaked classes page
This commit is contained in:
@@ -0,0 +1,43 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
// In the last chapter, we defined properties and methods on the class using the public keyword.
|
||||||
|
// You can also define them using the "protected" and "private" keywords.
|
||||||
|
// Both keywords prevent the properties and functions from being accessible outside the object.
|
||||||
|
// Only the object itself can use each.
|
||||||
|
class Phone
|
||||||
|
{
|
||||||
|
private $number;
|
||||||
|
|
||||||
|
public function setNumber($number)
|
||||||
|
{
|
||||||
|
$this->number = $number;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// We cannot set the number using "$phone->number = '123-456-7890'".
|
||||||
|
// Instead, we can use the public method.
|
||||||
|
$phone = new Phone();
|
||||||
|
$phone->setNumber('123-456-7890');
|
||||||
|
|
||||||
|
// Making an attribute or function private, gives you more control over the data in the object.
|
||||||
|
// For example, we could prevent a number being set if it starts with a 7.
|
||||||
|
class Phone2
|
||||||
|
{
|
||||||
|
private $number;
|
||||||
|
|
||||||
|
public function setNumber($number)
|
||||||
|
{
|
||||||
|
if (substr($number, 0, 1) !== '7') {
|
||||||
|
$this->number = $number;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The "protected" and "private" keywords work a little differently, but we
|
||||||
|
// will learn more about "protected" when we discuss inheritance.
|
||||||
|
// However, they both prevent functions and properties from being accessed outside an object.
|
||||||
|
class Phone3
|
||||||
|
{
|
||||||
|
private $number;
|
||||||
|
protected $caller;
|
||||||
|
}
|
||||||
|
@@ -24,9 +24,15 @@ $bike = new Bicycle();
|
|||||||
$bike->color = 'Blue';
|
$bike->color = 'Blue';
|
||||||
echo $bike->color . "\n";
|
echo $bike->color . "\n";
|
||||||
|
|
||||||
|
// An instance of a class is called an object. Congratulations!
|
||||||
|
// You are now performing object-oriented development.
|
||||||
|
$redBike = new Bicycle();
|
||||||
|
$redBike->color = 'Red';
|
||||||
|
echo $redBike->color . " Bike Object\n";
|
||||||
|
|
||||||
// A method is a function attached to the class. You can add a method
|
// A method is a function attached to the class. You can add a method
|
||||||
// to a class by using the "public" keyword followed by the function. A method
|
// to a class by using the "public" keyword followed by the function. A method
|
||||||
// can access the attributes and methods of the instance using the "$this" variable.
|
// can access the attributes and methods of an object instance using the "$this" variable.
|
||||||
class Tricycle
|
class Tricycle
|
||||||
{
|
{
|
||||||
public $color;
|
public $color;
|
||||||
|
Reference in New Issue
Block a user