Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Getting static variables from DataObjects or Controllers


Go to End


5 Posts   3535 Views

Avatar
micahsheets

Community Member, 165 Posts

26 June 2009 at 5:53am

Is there a way to get the value of a $protected variable on an object?

In the case of ModelAdmin, it has a protected $currentRecord so when I am in the ModelAdmin in the CMS I expected to be able to:

$record = Controller::curr()->currentRecord;

However that does not work. If I go into CMS/ModelAdmin.php and add:

function Record() {
return $this->currentRecord;
}

and then do:

$record = Controller::curr()->Record();

that works but I don't want to modify a core file like that if I don't have to.

Avatar
CrazyCoders

Community Member, 32 Posts

26 June 2009 at 5:57am

Well you just said it yourself, it is protected, so no, there is no way that you can access it from outside the scope of the object itself, that is what it's used for...

Private = Even inherited classes don't see it
Protected = Only inherited classes can see that property
Public = Anyone using this class can see the public members

Anything else i can do for you? :)

Avatar
micahsheets

Community Member, 165 Posts

26 June 2009 at 7:05am

Isn't "Controller::curr()-> " asking the class itself? If that is so then I should be able to access the protected var since it is the current class?

Avatar
CDGIDev

Community Member, 9 Posts

26 June 2009 at 7:12am

No Controller::Curr() is calling something called a Static function/property. Static elements cannot be anything else than public or they would be useless. The method you defined before about modifying the source file is pretty much the only workaround if ->currentRecord is private. If ->currentRecord is protected, then you can define that property/function inside your own class such as :

class MyModelAdmin extends ModelAdmin {

function Record() {
return $this->currentRecord;
} 

}

But note that this will not work if you are targeting a private property!

Avatar
micahsheets

Community Member, 165 Posts

26 June 2009 at 7:40am

It seems that even though the variable is protected using

function Record() {
return $this->currentRecord;
}

Doesn't work because $this isn't the controller.

The only way I can get it to work is to modify core. :(