Another "Yet another call to a member function function() on a non-object"
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 appropri开发者_如何学运维ate 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 $myRegExp
from within object scope.
You should probaby add a constructor to your validator:
public function __construct($re)
{
$this->myRegExp = $re;
}
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:
interface IValidator
{
public function valid($input);
}
Let your specific regex classes implement that interface:
class ValidateFnameAndLname implements IValidator
{
function valid($flname)
{
return preg_match("/[a-zA-Z' ']{2,}/", $flname);
}
}
And construct your Validate class like this:
class Validate
{
protected $myRegExp;
public function __construct(IValidator $validator)
{
$this->myRegExp = $validator;
}
//Sends each entry to corresponding RegExp function with appropriate regular expression
function validate_form($un, $fname)
{
$err_counter = 0;
if(!$this->myRegExp->valid($fname))
{
$error_identifier .= 'firstName+';
++$err_counter;
}
}
}
Then you are on your way to get a more coherent design.
I'm guessing this is the line giving you a problem?
if(!$this->myRegExp->validate_fname_and_lname($fname))
You use $this->myRegExp
, but thats not a member of the Validate class. You have $myRegExp declared as a global variable.
精彩评论