Belajar PHP OOP Part 1.11 : Visibility
- Visibility/ Access modifier adalah kemampuan properties, function dan constant dapat di akses dari mana saja
- Secara defaul properties, function, dan constant yang kita buat di dalam class bisa diakses dari mana saja, atau artinya dia adalah public
- Selain public, masih ada beberapa visibility lainnnya
- Secara default kata kunci var untuk properties adalah sifatnya public
<?php
class Product
{
private string $name;
private int $price;
public function __construct(string $name, int $price)
{
$this->name = $name;
$this->price = $price;
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): int
{
return $this->price;
}
}
<?php
require_once "data/Product.php";
$product = new Product("Apple", 10000);
//Error
echo $product->name . PHP_EOL;
echo $product->price . PHP_EOL;
Atau Akses via Function
<?php
require_once "data/Product.php";
$product = new Product("Apple", 10000);
echo $product->getName() . PHP_EOL;
echo $product->getPrice() . PHP_EOL;
Protected
<?php
class Product
{
protected string $name;
protected int $price;
public function __construct(string $name, int $price)
{
$this->name = $name;
$this->price = $price;
}
public function getName(): string
{
return $this->name;
}
public function getPrice(): int
{
return $this->price;
}
}
class ProductDummy extends Product
{
function info ()
{
echo "Name $this->name" . PHP_EOL;
echo "Price $this->price" . PHP_EOL;
}
}
<?php
require_once "data/Product.php";
$product = new Product("Apple", 10000);
echo $product->getName() . PHP_EOL;
echo $product->getPrice() . PHP_EOL;
$dummy = new ProductDummy("Dummy", 1000);
$dummy->info();