Codeigniter declaring class level variable in CI_Model class - php

I am new to PHP and Codeigniter, and I am declaring a class level variable which I wanted to access in model class. I'm getting an error that the variable is not defined. Here is my code:
class Country_model extends CI_Model{
protected $table = 'COUNTRY';
function __construct()
{ // Call the Model constructor
parent::__construct();
}
function retriveAll(){
$q = $this->db->from($table)
->order_by('ID','ASC')
->get();
if ($q->num_rows()>0){
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
}
I have declared $table and accessing in retriveAll function. Please help me.

That's not how you access class variables. Try using $this->table instead:
function retriveAll(){
$q = $this->db->from($this->table)
->order_by('ID','ASC')
->get();
if ($q->num_rows()>0)
{
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}

Access your class variable with $this, like:
$this->table

Related

Can't access global variable in PHP codeigniter Model class.

I have a class in Codeigniter which extends CI_Model.
I have declared a global array $data, but I can't access this array from my functions which i want to push some items.
that shows
A PHP Error was encountered Message: Undefined variable: data
and Fatal error: Cannot access empty property in /api/system/core/Model.php on line 51
code for class:
class Subscription_collection_model extends CI_Model {
public $data=array();
/*
|-----------------------------------------
| Constructor
|-----------------------------------------
*/
function __construct() {
parent::__construct();
}
function get() {
$this->db->select('family.house_name,family.id,family_grade.amount');
$this->db->from('family');
$this->db->join('family_grade','family_grade.id = family.family_grade_id');
$query = $this->db->get();
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$this->findBalance($row->id);
}
}
return $data;
}
function findBalance($id) {
$this->db->where('family_id', $id);
$this->db->select_sum('collecting_amount');
$query = $this->db->get('subscription_collection');
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
array_push($this->$data,$row->collecting_amount);
}
}
}
}
you got a typo there. you want to call $this->data not $this->$data.
the latter would assume, you wanna call a dynamic variable on the instance.
$prop = 'myProperty';
$this->$prop = 'test';
is the same as
$this->myProperty = 'test';
How about:
return $this->data;

PHP return NULL from __construct

I'm trying to write some classes which pull my data out of my database and create objects based on that data. I'm working with CodeIgniter.
The problem is that if an id is supplied to the __construct method but no row in the database table has that id, an object is returned but with all the properties set to NULL.
Is there a way that I can check this and return NULL instead of an object if there is no corresponding row?
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
...
public function __construct($id = NULL){
if($id){
$this->getFromDatabase($id);
}
}
...
function getFromDatabase($id){
foreach($this->database_keys as $key){
$this->db->select($key);
}
$this->db->from($this->database_table_name);
$this->db->where('id', $id);
$this->db->limit(1);
$q = $this->db->get();
if ($q->num_rows() > 0){
foreach($q->result() as $property){
foreach($property as $key => $value){
$this->$key = $value;
}
}
} else {
// NEED TO SET THE OBJECT TO NULL FOR THIS CASE
}
}
...
}
Any help would be appreciated.
This is not possible, once __construct is called, you will receive an object instance.
The correct way to handle this is to throw an Exception from inside the constructor.
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
public function __construct($id = NULL){
if($id){
$row = $this->getFromDatabase($id);
if (!$row) {
throw new Exception('requested row not found');
}
}
}
}
try {
$record = new JS_Model(1);
} catch (Exception $e) {
echo "record could not be found";
}
// from here on out, we can safely assume $record holds a valid record
why dont you make your constructor private and use a method such as GetInstance(); something like this. Syntax may be incorrect as i dont write much php anymore :-(.
class JS_Model extends CI_Model
{
protected $database_table_name;
protected $database_keys;
...
private function __construct($id = NULL){
}
public static function GetInstance($id)
{
$x = new JS_Model($id);
$x->getFromDatabase($id);
if(is_object($x))
{
return $x;
}
return null;
}
...
function getFromDatabase($id){
foreach($this->database_keys as $key){
$this->db->select($key);
}
$this->db->from($this->database_table_name);
$this->db->where('id', $id);
$this->db->limit(1);
$q = $this->db->get();
if ($q->num_rows() > 0){
foreach($q->result() as $property){
foreach($property as $key => $value){
$this->$key = $value;
}
}
} else {
return null;
}
}
...
}

Cannot use right the inheritance in PHP class

I have this parent class in PHP:
class parentClass{
public $table;
public function __construct(){
$this->table = "my_parent_table";
}
public function getName($id) {
$strQuery = "SELECT name FROM $this->table WHERE id=$id";
$result = mysql_query($strQuery);
if ($result) {
$row = mysql_fetch_object($result);
if ($row) {
return $row->name;
} else {
return false;
}
} else {
return false;
}
}
}
And I have also another class with inherits this one:
class childClass extends parentClass{
public $table;
public function __construct(){
$this->table = "my_child_table";
}
}
Then in another file I am doing:
$myObj = new childClass();
$name = $myObj->getName('1');
The problem now is that the getName function has a null table, so the variable $this->table is null, while I want it to be ""my_child_table" as long as I have a childClass object.
Does anyone know what I am doing wrong?
Thanks in advance
Not sure, but this look tricky:
class childClass extends parentClass{
public $table;
The parentClass already defines a $table, so it's likely that redeclaring it inside the child class will clobber the parent's version. You have to remove the declaration here. Also, public visibility doesn't really encapsulate the state very well; use protected in the parent instead.
public function __construct()
{
You should add parent::__construct() here (unless parent only sets $this->table, but even then it's good to add)
$this->table = "my_child_table";
}
}

PHP set data by var name

I have class
class User extends BaseModel{
public $id;
public $name;
}
class BaseModel{
function __construct($data=null){
if($data!=null)
//set $id and $name
}
}
I would like to set $id , $name and any other data that extends BaseModel by calling
$test = new User(array('id'=>1,'name'=>'user name'))
I tried to use
$this->__set($arrayKey,$arrayValue);
But i got error : Fatal error: Call to undefined method User::__set()
What am I doing wrong?
Thank you for any help.
Just loop through the data and assign each property:
class BaseModel {
function __construct($data = NULL) {
foreach ((array) $data as $k => $v) {
$this->$k = $v;
}
}
}
The reason you got the error about __set() not being defined is because you didn't define it. Although __set() is a magic method, you do still have to define it's behavior if you want to do something with it.
http://www.php.net/manual/en/language.oop5.overloading.php#object.set
__set is run when writing data to inaccessible properties
This means if you try to "set" a class variable in a scope you're not allowed to (like a private or protected variable), this function will run.
class Test {
private $var;
}
$c = new Test;
$c->var = 1; // Error, or call __set if defined
foreach ($data as $key => $value) {
$this->$key = $value;
}
Try this
class BaseModel{
function __construct($data=null){
if($data!=null)
{
//set $id and $name
$this->id = $data['id'];
$this->name = $data['name'];
}
}
}

PHP class: Unable to access array in another function

I tried a lot of search but unable to figure out why array $wordlinks in function DoWordLink is not carrying values from function __construct. PHP class code as below:
<?php
class autolinkkeyword
{
public $wordlinks = array();
public function __construct(){
$query = mysql_query("SELECT keyword FROM library");
while ($row = mysql_fetch_array($query))
{
$this->wordlinks [$row["keyword"]] = $row["keyword"];
}
}
public function linkkeywords ($posts)
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
$wl=array_keys($this->wordlinks);
$pm="/((?<=\s|^)(?:" . implode('|',$wl) .")(?=\.|\!|\?|\,|\'|\s|$))/im";
foreach($posts as $key => $mainbody)
{
$mainbody=preg_replace_callback($pm, 'DoWordLink', $mainbody) ;
echo $mainbody;
}
}
}
?>
You can make it an actual method of that class and call it using this method:
http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback
like:
preg_replace_callback($pm, array($this, 'DoWordLink'), $mainbody);
Change DoWordLink function so it is part of the class like:
class autolinkkeyword
{
function DoWordLink($match)
{
$rpl=$match[1];
if(isset($this->wordlinks[$rpl]))
{
$kword = $this->wordlinks[$rpl];
$rpl="<a class=\"keyword_link\" href=\"#\" onclick=\"popup('popUpDiv');
ajax_loadContent('kword', 'library.php?keyword=$kword')\">$kword</a>";
unset($this->wordlinks[$match[1]]);
}
return $rpl;
}
}
aren't you missing a "this->" construct here? if(isset($this->wordlinks[$rpl]))
Use the $this everywhere you refer to $wordlinks.
$this->wordlinks
You need to access the property in your linkkeywords-method with the object-accessor, too!
public function linkkeywords ($posts)
{
// Here use $this->wordlinks not $wordlinks
}

Categories