I am learning Laravel and have an eloquent model. I have a public static function and I can access a public static property from the class.
How do you access a private property? Should I just make them all public? I either get undeclared static property.
Can you only access these through the __contstruct method?
In OOP:
private - you can access that property only from inside the class
class Private
{
private $foo;
function setFoo($foo)
{
$this->foo = $foo;
}
function getFoo()
{
return $this->$foo
}
}
$privateObj = new Private;
$privateObj->foo = 'bar'; // Returns error
echo $privateObj->foo; // Returns error
$privateObj->setFoo('bar') // Sets the $foo parameter = 'bar';
echo $privateObj->getFoo() // Returns 'bar';
public - you can access that property from an object
class Public
{
public $foo;
function setFoo($foo)
{
$this->foo = $foo;
}
function getFoo()
{
return $this->$foo
}
}
$publicObj = new Public;
$publicObj->foo = 'bar'; // Sets the $foo parameter = 'bar';
echo $publicObj->foo; // Returns 'bar';
$publicObj->setFoo('bar') // Sets the $foo parameter = 'bar';
echo $publicObj->getFoo() // Returns 'bar';
protected - you can access that property from inside the class and from inside of class's children
class Protected
{
protected $foo;
function setFoo($foo)
{
$this->foo = $foo;
}
function getFoo()
{
return $this->$foo
}
}
class ProtectedChild extends Protected
{
}
$protectedChildObj = new ProtectedChild;
$protectedChildObj->foo = 'bar'; // Returns error
echo $protectedChildObj->foo; // Returns error;
$protectedChildObj->setFoo('bar') // Sets the $foo parameter = 'bar';
echo $protectedChildObj->getFoo() // Returns 'bar';
Hope this helps
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community