Fatal error: Using $this when not in object context in plugins/newsarticles/controller/NewsArticleController.php on line 29
I can see where it is erroring, line 29 is this line:
$sqlFetch = $this->model->getAllNewsArticlesByDate();
Below I have submitted my code, can anyone shed any light on this?
<?php
require_once("plugins/newsarticles/model/NewsArticleDB.php");
class NewsArticleController
{
private $model;
public function __construct()
{
$this->model = new NewsArticleDB();
} //end constructor
/**
*Grab all the News Articles using the function
*Filter by date
*return the most recent 10
*/
function newsArticleHome()
{
//Grab the News Articles by date
$sqlFetch = $this->model->getAllNewsArticlesByDate();
foreach ($sqlFetch as $row)
{
//Insert posts into an object array
$objNewsArticle[] = new NewsArticle($row['newsId'],$row['newsTitle'], $row['newsPreview'], $row['newsDisplayPicture'], $row['newsContet']." ".$row['newsCategories'], $row['newsSubmissionDate']);
}
//Count the array incase it's less than 10 posts
//If it's more than 10, then set to 10, if it's less then set to x
if(count($objNewsArticle) > 10)
{
$tempObjectCount = 10;
}
else
{
$tempObjectCount = count($objNewsArticle);
}
//Store them in an array for output
for($tempLoopNumber = 0; $tempLoopNumber<$tempObjectCount; $tempLoopNumber++)
{
$recentNewsArticles[$tempLoopNumber] = $objNewsArticle[$tempLoopNumber];
}
return $recentNewsArticles;
}
function newsArticleId($id)
{
//Grab the Posts by date
$sqlFetch = $this->model->getAllNewsArticlesByDate();
$tempOptions = $sqlFetch->fetchAll();
$tempOpNumber = count($tempOptions);
for($tempNewsArticleNumber = 0; $tempNewsArticleNumber<$tempOpNumber; $tempNewsArticleNumber++)
{
if($tempOptions[$tempNewsArticleNumber]['newsId'] == $id)
{
$singlePost = $tempOptions[$tempNewsArticleNumber];
}
}
return $singlePost;
}
} //end class
?>
I am calling this from another file named testing:
include_once("plugins/newsarticles/controller/NewsArticleController.php");
echo "out";
echo NewsArticleController::newsArticleHome();
NewsArticleController::newsArticleHome(); is calling the function as if it were a static function. You need rather to create an instance of the class.
$nacont = new NewsArticleController();
$nacont->newsArticleHome();
Related
I am building a genetics calculator, and have reduced my code to a simple format to explain my issue.
I basically have this line which instantiates a hatch object:
$hatch = new Hatch($maleGeneticsPOST, $femaleGeneticsPOST, 'leopardGecko', true);
This takes a form post for the parent genetics and sets the species type. Below is my Parent class and Child class to show how this essentially works:
class Genetics
{
public $species = '';
public $dominants = [];
public $recessives = [];
public $snows = [];
public $wildtypes = [];
function __construct($species)
{
$this->species = $species;
echo $species; // returns leopardGecko as expected
}
}
class Hatch extends Genetics
{
function __construct($father, $mother, $species, $autoHatch = true, $hatchMethod = "punnett")
{
parent::__construct($species);
// Other code for $father, $mother etc.
}
}
On the face of it, those 2 classes are working well with each other, I can set the species type in the object and Hatch will set the parent to it.
However, what I am struggling to do is to then use the $species property in the parent to set the genetics, based off of the species selected/set; here's an example:
class Genetics
{
public $species = '';
public $dominants = [];
public $recessives = [];
public $snows = [];
public $wildtypes = [];
function __construct($species)
{
$this->species = $species;
echo $species; // returns leopardGecko as expected
if($species === "leopardGecko"){
$this->dominants = ['NN', 'BB', 'TT'];
$this->recessives = ['Bb', 'Tt', 'Rr'];
$this->snows = ['Mm', 'Gg'];
$this->wildtypes = ['QQ', 'Qq'];
}
}
}
And when I try and use them further down in my Hatch class, they just return empty arrays:
foreach ($alleles as $allele) {
//echo $this->allGenetics[$allele].' ';
if (in_array($allele, $this->dominants, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Dominants'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Dominants'], $allele);
} elseif (in_array($allele, $this->recessives, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Recessives'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Recessives'], $allele);
} elseif (in_array($allele, $this->wildtypes, true)) {
//echo $this->allGenetics[$allele].' ';
array_push($geckoGenetics['Gecko']['Wildtypes'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gecko']['Recessives'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Wildtypes'], $allele);
array_push($geckoGenetics['Gene']['Recessives'], $allele);
} elseif (in_array($allele, $this->snows, true)) {
array_push($geckoGenetics['Gecko']['Snows'], $this->allGenetics[$allele]);
array_push($geckoGenetics['Gene']['Snows'], $allele);
}
}
Please note: The rest of that code works fine, I'm just talking about the $this->dominants, $this->recessives, $this->wildtypes & $this->snows variables - they return empty.
Am I missing something obvious? This is my first proper go at OOP and it's going well, apart from this bit!
'There is a difference in how you're calling the field $species and how you're trying to do so with $dominants. If you want to access fields outside of the scope of your function, you'll need to call them using $this->.
So in the constructor, if you replace the following:
public $dominants = ['NN', 'BB', 'TT'];
public $recessives = ['Bb', 'Tt', 'Rr'];
public $snows = ['Mm', 'Gg];
public $wildtypes = ['QQ', 'Qq'];
with:
$this->dominants = ['NN', 'BB', 'TT'];
$this->recessives = ['Bb', 'Tt', 'Rr'];
$this->snows = ['Mm', 'Gg'];
$this->wildtypes = ['QQ', 'Qq'];
It should work.
I'm using custom class to connect to asterisk server via php.
Here it's code:
class Asterisk_ami
{
public $ini = array();
function __construct ()
{
$this->ini["con"] = false;
$this->ini["host"] = "127.0.0.1";
$this->ini["port"] = "****";
$this->ini["lastActionID"] = 0;
$this->ini["lastRead"] = array();
$this->ini["sleep_time"]=1.5;
$this->ini["login"] = "****";
$this->ini["password"] = "****";
}
function __destruct()
{
unset ($this->ini);
}
public function connect()
{
$this->ini["con"] = fsockopen($this->ini["host"], $this->ini["port"],$a,$b,10);
if ($this->ini["con"])
{
stream_set_timeout($this->ini["con"], 0, 400000);
}
}
public function disconnect()
{
if ($this->ini["con"])
{
fclose($this->ini["con"]);
}
}
public function write($a)
{
$this->ini["lastActionID"] = rand (10000000000000000,99999999900000000);
fwrite($this->ini["con"], "ActionID: ".$this->ini["lastActionID"]."\r\n$a\r\n\r\n");
$this->sleepi();
return $this->ini["lastActionID"];
}
public function sleepi ()
{
sleep($this->ini["sleep_time"]);
}
public function read()
{
$mm = array();
$b = array();
$mmmArray=array();
$k = 0;
$s = "";
$this->sleepi();
do
{
$s.= fread($this->ini["con"],1024);
sleep(0.005);
$mmm=socket_get_status($this->ini["con"]);
array_push($mmmArray, $mmm);
} while ($mmm['unread_bytes']);
$mm = explode ("\r\n",$s);
$this->ini["lastRead"] = array();
for ($i=0;$i<count($mm);$i++)
{
if ($mm[$i]=="")
{
$k++;
}
$m = explode(":",$mm[$i]);
if (isset($m[1]))
{
$this->ini["lastRead"][$k][trim($m[0])] = trim($m[1]);
}
}
unset ($b);
unset ($k);
unset ($mm);
unset ($mm);
unset ($mmm);
unset ($i);
unset ($s);
var_dump($mmmArray);
return $this->ini["lastRead"];
//return $s;
}
public function init()
{
return $this->write("Action: Login\r\nUsername: ".$this->ini["login"]."\r\nSecret: ".$this->ini["password"]."\r\n\r\n");
}
}
And here is testAsterisk.php where I try it.
include("./lib/asteriskAmi.php");
$a = new Asterisk_ami();
$a->connect();
if ($a->ini["con"])
{
$a->init();
$a->write("Action: GetConfig\r\nFilename: extensions.conf\r\n");
print_r($a->read());
$a->disconnect();
}
I want to get extension.conf config via ami. The problem is that I don't get full config. 16 last string are alwas missing. However when I check GetConfig via asterisk console it returns full config.
As you can see while cycle is interrupted when unread bytes of socket_get_status are 0, I checked them pushing in array and dumping it, and I can see that unread_bytes are actually 0. I tried changing sleep_time and different timeout parametres, the result was the same.
What else can I check? What can cause this mistake? May be I can use some other func?
Really, only proper solution I've found is to use PAMI, instead of custom class. It's more comfortable for using and anyway it gives me full content of extensions.conf.
I am using FPDF to create a report from a Mysql database. The PDF is created fine but I would like to display the headers for each column at the top of every page for easier navigation. Does anyone have any idea on how to do this?
Thanks for the help.
try to extend fpdf class, and implement your Ln function: every time you add a line, decrement counter of line number, and when is 0, add new page with header.
class _PDF extends FPDF
{
var $_num_Rows = null;
var $_heightCell = null;
const NUM_ROWS = 48; // set number line in page
function _PDF($orientation = 'P',$unit = 'mm' ,$page = 'A4')
{
$this->_numRows = self::NUM_ROWS;
$this->_heightCell = 4;
$this->SetAutoPageBreak(true,10);
$this->FPDF($orientation, $unit, $page);
}
public function init_numRows()
{
$this->_numRows = self::NUM_ROWS;
}
public function dec_numRows()
{
$this->_numRows--;
}
function Ln()
{
if ( $this->_numRows )
{
parent::Ln();
$this->dec_numRows();
}
else
{
$this->addHeader();
}
}
function addHeader()
{
$this->init_numRows();
$this->AddPage();
// ...
}
}
$pdf = new _PDF();
Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.
What is the corecte way to handle with al lot objects of the same type?
Example:
When i get a list of notes from the database with zend framework i get a rowset which contains an array with note data.
If the number of notes in the database is 20 records large it's no problem to create a note object for every note in the database. But if the database contains 12.500 note records what shall i do than? Try to create 12.500 objects is possible but it's shure isn't quick enough.
Ty, Mark
This is the code i use.
Code to get the data from the database:
if (is_numeric($id) && $id > 0) {
$select = $this->getDao()->select();
$select->where('methode_id = ?', $id);
$select->order('datum DESC');
$rowset = $this->getDao()->fetchAll($select);
if (null != $rowset) {
$result = $this->createObjectArray($rowset);
}
}
createObjectArray function:
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
foreach ($rowset as $row) {
$model = new Notes();
$this->populate($row, $model);
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}
}//endforeach;
return $result;
}
Populate function
private function populate($row, $model)
{
// zet de purifier uit om overhead te voorkomen
if (isset($row['id'])) {
$model->setId($row['id']);
}
if (isset($row['type'])) {
$model->setType($row['type']);
}
if (isset($row['tekst'])) {
$model->setLog($row['tekst']);
}
if (isset($row['methode_id'])) {
$model->setSurveyMethodId($row['methode_id']);
}
if (isset($row['klant_id'])) {
$model->setCustomerId($row['klant_id']);
}
if (isset($row['gebruiker_aangemaakt_tekst'])) {
$model->setCreatedByUser($row['gebruiker_aangemaakt_tekst']);
}
if (isset($row['gebruiker_gewijzigd_tekst'])) {
$model->setUpdatedByUser($row['gebruiker_gewijzigd_tekst']);
}
if (isset($row['gebruiker_aangemaakt'])) {
$model->setCreatedByUserId($row['gebruiker_aangemaakt']);
}
if (isset($row['gebruiker_gewijzigd'])) {
$model->setUpdatedByUserId($row['gebruiker_gewijzigd']);
}
if (isset($row['datum_aangemaakt'])) {
$model->setDateCreated($row['datum_aangemaakt']);
}
if (isset($row['datum_gewijzigd'])) {
$model->setDateUpdated($row['datum_gewijzigd']);
}
$model->clearMapper();
return $model;
}
You could page your requests, so you only get a set amount of notes back each time. Although I can't see a problem with "only 12,500" objects, unless your object creation is doing something costly, i.e more queries on the database etc.
I am not so sure about your question.
For eg :
//Create a single object
$obj = new NoteObject();
//Set the properties if it differs
$obj->setX( $row );
//Make use of the method
$obj->processMethod();
So this way you just need a single object. Lets see the code if its not to give you a right answer.
Edit :
What I thought was in
protected function createObjectArray(Zend_Db_Table_Rowset_Abstract $rowset)
{
$result = array();
//Create the model here
$model = new Notes();
foreach ($rowset as $row) {
//Yes populate the values
$this->populate($row, $model);
/*
And not like saving the object here in array
if (isset($row['id'])) {
$result[$row['id']] = $model;
} else {
$result[] = $model;
}*/
//Do some calculations and return the result in array
$result[$row['id']] = $this->doSomething();
}//endforeach;
return $result;
}
I am not sure why you are keeping this object there itself. Any reuse ? the probably paginate and do :-)