How come a simple instantiation doesn’t work? I have been doing the same method to all of the classes I created/instantiated but this is the only one that’s giving me this kind of error.
Fatal error: Call to a member function validate_fname_and_lname() on a non-object in /homepages/......../Validate.php on line 23
Here’s my code:
//Class Validate
<?php
require_once 'RegExp.php';
$myRegExp = new RegExp();
class Validate
{
//Sends each entry to corresponding RegExp function with appropriate regular expression
function validate_form($un, $fname)
{
$err_counter = 0;
if(!$this->myRegExp->validate_fname_and_lname($fname))
{
$error_identifier .= 'firstName+';
++$err_counter;
}
}
}
//Class RegExp
<?php
class RegExp
{
function validate_fname_and_lname($flname)
{
return preg_match("/[a-zA-Z' ']{2,}/", $flname);
}
}
I think you are trying to access the global
$myRegExpfrom within object scope.You should probaby add a constructor to your validator:
And then instantiate your Validator like this:
$validator = new Validate($myRegExp);And you should declare a member variable ‘myRegExp’ in your Validate class.
And on a side note: I think you should rethink your design. If I were you I’d create an interface:
Let your specific regex classes implement that interface:
And construct your Validate class like this:
Then you are on your way to get a more coherent design.