I'm new to PHP but come from a Java background and I'm trying to implement a simple strategy pattern in OO-PHP.
I'm having a problem with variable scope and assigning an object to a class property. I get an error saying that the property $strategy is undefined when trying to access from the metric constructor. Can anyone help?
Thanks, John
Strategy Pattern Code:
interface iMetric{
public function calculateReadability($text);
}
/*Context - strategy pattern.*/
class metric{
private $strategy;
function __construct($metric){
$this->$strategy = $metric;
}
function calculateReadability($text){
return $this->$strategy->calculateReadability($text);
}
}
Where this is being constructed/called from: class fleschEase implements iMetric{
function calculateReadability($text){
require_once('textstats/TextStatistics.php');
$statistics = new TextStatistics();
return $statistics->flesch_kincaid_reading_ease($text);
}
}
require_once('metrics.php');
// Flesch Reading Ease
if(strlen($fleschReadingEase)==0){
$metric = new metric(new fleschEase());
$fleschReadingEase = $metric->calculateReadability($content);
}
This is a syntax issue, try this:
function __construct($metric){
$this->strategy = $metric;
}
Properties in PHP have the dollar when they are defined but not when they are used.