You can use this method in any php file, i.e. a template, controller, snippet whatever. It is not possible to use php code in a text file, it would not be executed but simply stored as a string.
I donβt really see your use case for storing the code in a text file, anyway?
If you want to pass an argument:
page::$methods['age'] = function($page, $date) {
$then = date('Ymd', strtotime($date));
$diff = date('Ymd') - $then;
return substr($diff, 0, -4);
};
Then call like this
$page->age($page->date());
// or whatever the field is that you want to transform
But since you probably want to calculate the value from an existing field, Iβd suggest using a field method instead of a page method.
Edit: I forgot that this does not work with a field called date, because the date field is a special field that returns an integer instead of a field object. So you would have to call the field that contains the date something else, lets call it birthday in this case:
field::$methods['toAge'] = function($field) {
// create a DateTime object from the field that is not called `date`
$d1 = new DateTime($field->value());
// create a DateTime object from the current date
$d2 = new DateTime(date('ymd'));
// get the difference
$diff = $d2->diff($d1);
// return the number of years
return $diff->y;
};
In your template:
echo $page->birthday()->toAge();
Edit: with the field method above, and a field called date, you can also do this:
echo $page->content()->date()->toAge();