PHP OOP Access modifiers

Access Modifiers Outside of class In Derived class
public Yes Yes
protected No Yes
private No No

public access modifiers

class App{
	public $price=3000;
}
$app = new App();
echo "Price: $app->price <hr>";


class Software extends App{
	public function store(){
		echo "Software store price: $this->price <hr>";
	}
}

$software = new Software();
$software->store();

protected access modifiers

class AppProtected{
	protected $price=3000;
}
$app = new AppProtected();

// unable to access
// echo "Protected Price: $app->price <hr>";


class SoftwareProtected extends AppProtected{
	public function store(){
		echo "Software store price(Accessing protected price): $this->price <hr>";
	}
}

$software = new SoftwareProtected();
$software->store();

private access modifiers

class AppPrivate{
	private $price=3000;
}
$app = new AppPrivate();
// unable to access outside of class
// echo "Price: $app->price <hr>";


class SoftwarePrivate extends AppPrivate{
	public function store(){
		// unable to access within child class
		// echo "Software store price: $this->price <hr>";
	}
}

$software = new SoftwarePrivate();
$software->store();
© 2016 - 2022, All Rights are Reserved.