The model is in the vendor folder (normal package). I need to access an attribute of the model which is protected. NOTE: Not possible of making a getter in the model class.
Asked
Active
Viewed 1,079 times
0
-
1Hard to tell without seeing the code and how you are using it. Can you extend the class? – jeroen Nov 14 '17 at 12:24
-
I can extend the class yes. – Ardit Nov 14 '17 at 12:25
-
So extend it and put your getter there. That will obviously only work with objects of that class that you create yourself... – jeroen Nov 14 '17 at 12:25
-
Probably a duplicate of this [topic](https://stackoverflow.com/questions/20334355/how-to-get-protected-property-of-object-in-php), take a look. – Claudio Nov 14 '17 at 12:26
-
Not really @claudio. In my case I dont have a way to modify the model because its on the vendor folder. – Ardit Nov 14 '17 at 12:28
-
Ok @Ardit, then you need to extend that class. Post some code if you need help with that. – Claudio Nov 14 '17 at 12:30
-
Once I extended a vendor class so that I could access some protected variables... and later I discovered I just needed to create a config file and then the original class would read the values from there. So I actually didn't need to extend the class. Just saying because if you need to extend a class only to access a variable, maybe you are using that class wrong. (By the way, the class was Cartalyst Sentinel. – Amarnasan Nov 14 '17 at 13:54
2 Answers
1
To access a class property that is marked as protected you need to extend that class. Note that if that class is marked as final, you won't be able to do it.
Example:
class Parent {
protected $property;
}
class Child extends Parent {
public function getProperty()
{
return $this->property;
}
}

Claudio
- 5,078
- 1
- 22
- 33
1
The only way to get a protected variable is by a get-method in the class or by extending the class itself.
If you are not able to modify the class in question, then you have to extend the class with your own and create a getter function.

Tobias
- 65
- 7