/    Sign up×
Community /Pin to ProfileBookmark

public protected private

im a bit confused. ive been googling around and came across this explination

https://stackoverflow.com/questions/4361553/what-is-the-difference-between-public-private-and-protected
i am referring to shankars post
in his post in the protected explination he instantiated the grandpa class and tries to access the name property but says it would return a fatal error. but with the child class daddy it has no problem of accessing the name property. why is that??

to post a comment
PHP

2 Comments(s)

Copy linkTweet thisAlerts:
@NogDogAug 28.2019 — Did you start with the official explanation? https://www.php.net/manual/en/language.oop5.visibility.php
Copy linkTweet thisAlerts:
@NogDogAug 28.2019 — PS: Quick example I threw together:
<i>
</i>&lt;?php

class Foo
{
public $one = 1;
protected $two = 2;
private $three = 3;
}

class Bar extends Foo
{
public function test($name)
{
if(isset($this-&gt;$name))
{
echo "This worked: '$name' is {$this-&gt;$name}n";
}
else
{
echo "Nothing found for '$name'n";
}
}
}

$test = new Bar();
foreach(array('one', 'two', 'three') as $name) {
echo "$name:n";
$test-&gt;test($name);
if(isset($test-&gt;$name))
{
echo '$test-&gt;$name = '.$test-&gt;$name."n";
}
else
{
echo '$test-&gt;$name is not known.'."n";
}
}

Output:
<i>
</i>one:
This worked: 'one' is 1
$test-&gt;$name = 1
two:
This worked: 'two' is 2
$test-&gt;$name is not known.
three:
Nothing found for 'three'
$test-&gt;$name is not known.
×

Success!

Help @coleio spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.13,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...