Note that there are some explanatory texts on larger screens.

plurals
  1. PO$this in Array of Closures in Class
    text
    copied!<p>Say there is a class for objects, let's use a User as an example. The User class contains it's own Rules to validate it's data before submitting. Before saving to the database, the Rules will be checked and any errors will be returned. Otherwise the update will run.</p> <pre><code>class User extends DBTable // contains $Rules, $Data, $Updates, and other stuff { public __construct($ID) { parent::__construct($ID); // I'll only list a couple rules here... $this-&gt;Rules['Email'] = array( 'Empty' =&gt; 'ValidateEmpty', // pre-written functions, somewhere else 'Invalid' =&gt; 'ValidateBadEmail', // they return TRUE on error 'Duplicate' =&gt; function($val) { return existInDatabase('user_table', 'ID_USER', '`Email`="'. $val .'" AND `ID_USER`!='. $this-&gt;ID);} ); $this-&gt;Rules['Password'] = array( 'Empty' =&gt; 'ValidateEmpty', 'Short' =&gt; function($val) { return strlen($val) &lt; 8; } ); this-&gt;Rules['PasswordConfirm'] = array( 'Empty' =&gt; 'ValidateEmpty', 'Wrong' =&gt; function($val) { return $val != $this-&gt;Updates['Password']; } ); } public function Save(&amp;$Errors = NULL) { $Data = array_merge($this-&gt;Data, $this-&gt;Updates); foreach($this-&gt;Rules as $Fields =&gt; $Checks) { foreach($Checks as $Error =&gt; $Check) { if($Check($Data[$Field])) // TRUE means the data was bad { $Errors[$Field] = $Error; // Say what error it was for this field break; // don't check any others } } } if(!empty($Errors)) return FALSE; /* Run the save... */ return TRUE; // the save was successful } } </code></pre> <p>Hopefully I posted enough here. So you'll notice that in the <strong>Duplicate</strong> error for Email, I want to check that their new email does not exist for any other user excluding themselves. Also <strong>PasswordConfirm</strong> tries to use $this->Updates['Password'] to make sure they entered the same thing twice.</p> <p>When Save is run, it loops through the Rules and sets any Errors that are present.</p> <p><strong>Here is my problem:</strong></p> <pre><code>Fatal error: Using $this when not in object context in /home/run/its/ze/germans/Class.User.php on line 19 </code></pre> <p>This error appears for all closures where I want to use $this.</p> <p>It seems like the combination of closures in an array and that array in a class is causing the problem. This Rule array thing works fine outside of a class (usually involving "use") and AFAIK closures are supposed to be able to use $this in classes.</p> <p>So, solution? Work-around?</p> <p>Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload