It’s kinda hard to explain what I mean, I don’t know how to name this pattern, so I’ll explain with an example:
First.php:
<?php
class MyClass
{
public $Meaning = 42;
public function MyFun
{
include("Second.php");
}
}
?>
Second.php:
<div><?= $this->Meaning ?></div>
In the Second.php we rely on being included from a method in MyClass, and use the $this variable. Somehow this feels… unnatural to me. Maybe it’s because of my C# background, but I strongly feel that functions don’t span files. Classes might, but not functions (OTOH spanning classes is exactly what PHP does not allow).
So… am I being unreasonable in this, or is this really considered a bad practice? Or perhaps in view-logic (think MVC) this is even the standard approach?
I wouldn’t call it a bad practice. It does look a little unusual, but there are advantages. The main one as I see it is that you can access any member functions of the view (they would presumably be some kind of helpers) and do it polymorphically.
I don’t know if the polymorphic capability makes much sense (will there be a hierarchy of views?) — but if it does, this is a good syntax to access it.
Plus, there’s also the minor message that the code in
second.phpgives off: “this is the view”. Which is nice.