Trying to get property of non-object in OOP php [duplicate] - php

This question already has answers here:
Call to a member function on a non-object [duplicate]
(8 answers)
Closed 9 years ago.
I just want to back my class properties so that I can use them. In my project I want to fetch all result of mysql table data and return it. Well it works well, but alter returning data the error message has come which is given below:
Trying to get property of non-object in E:\xampp\htdocs\myProject\new_27_03\login_con.php on line 26
My code ::
nonClass.php
<?php
$doc = new Dortor(); // object
$doc->result("SELECT * FROM doctor"); // function call
foreach( $doc as $doctor ) {
echo $doctor->doc_name; // error msg: Trying to get property of non-object in
//E:\xampp\htdocs\myProject\new_27_03\login_con.php on line 26
}
?>
dortor.php
<?php
class Dortor extends DatabaseObject {
public $table_name = "doctor";
public $id;
public $doc_name;
public $doc_pass;
public $doc_img; // image directory
public function result($sql="") {
$result = $database->query($sql); // run query from mysql database
$result_array = array();
while( $row = $database->fetch_array($result) ) { // this while loop return actual result
$result_array[] = $this->get_table_value($row);
}
return $result_array;
}
}
?>
databaseObject.php
<?php
class DatabaseObject {
public function get_table_value($record) {
$className = get_called_class(); // get the class name
$object = new $className; // object call
$arrayValue = array();
$i=0; // inital array position
foreach( $object as $key => $value ) {
$arrayValue[$i] = $key; // get the class's object attributes
$i++;
}
$i = 1;
foreach ($record as $key => $value) { // fetch the database result
if(array_key_exists($key, $arrayValue) ) { // check if database's column name is exist on 'arrayValue' array,
$object->$arrayValue[$i] = $value; // if exist then, store value in 'Doctor' class's object attributes
$i++;
}
}
return $object;
}
}
?>

Your error is probably here:
$doc = new Dortor(); // object
$docs = $doc->result("SELECT * FROM doctor"); // you forgot to assign the result
foreach ($docs as $doctor) { // was looping over $doc here, instead of the result
echo $doctor->doc_name;
}

It would also make sense to check the correct variable type before the foreach loop starts:
if ( is_array( $doc) )
{
foreach( $doc as $doctor )
{
// foreach code
}
}
else
{
echo '$doc is no valid object';
var_dump($doc);
}
So you can find out, that's the problem.

Related

PHP Serialize list of objects to json comming null

I'm trying to pass a list of objects in php to a json but the output is not being as expected.
Controller:
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
require_once "../dao/SubstanciaDAO.php";
require_once "../utils/php/Serialize.php"; // importing util to serialize list of objects
if(array_key_exists("fetchAll",$_GET))
{
$subs = SubstanciaDAO::read(array("all"));//fetching list of objects
if($subs) {
$list = jsonSerializeList($subs);//this function is written bellow in another file
if(isset($list))
echo json_encode($list, JSON_UNESCAPED_UNICODE);//writting output
else
echo "Erro";
}
}
}
Util to serialize list of objects:
First try:
function jsonSerializeList( array $arr ) {
$res = array();
foreach ($arr as $a) {
$aux = get_class_vars(get_class($a));
array_push($res, $aux);
}
return $res;
}
Output:
[[],[],[]]
Second try:
function jsonSerializeList( array $arr ) {
$res = array();
foreach ($arr as $a) {
$aux = get_object_vars($a);
array_push($res, $aux);
}
return $res;
}
Output:
[[],[],[]]
Conclusion
My guess is that there is a problem with the class's private attributes.
In the "$ subs" object list, each position is an object of the "Sustancia.php" class:
class Substancia {
private $id;
private $principioAtivo;
private $nomeComercial;
private $apelidos;
public function __construct() {
$this->apelidos = array();
}
...
Would it be possible to correct the "jsonSerializeList" function so that it works correctly? I really need a function that does this object serialization to use whenever necessary.

Laravel eloquent duplicating data when using create method

I have a simple array thats returned when executing:
$this->forecast($value->id,$value->db_connection)
when I call the $reports::create($data) it duplicates each row, i have added some logic to print out $data within the foreach and it never returns duplicates, when printing the $result object it has 2 entries.
any idea where i am going wrong?
public function store() // function to store report data in db
{
$reports = new Reports;
$companyData = new ClientSettings;
$settings = $companyData::all();
foreach ($settings as $value) {
$data = $this->forecast($value->id,$value->db_connection);
$result = $reports::create($data);
}
echo "Forecast generated";
}
public function store() // function to store report data in db
{
$reports = new Reports;
$companyData = new ClientSettings;
$settings = $companyData::all();
foreach ($settings as $value) {
$data = $this->forecast($value->id,$value->db_connection);
$result = Reports::create($data);
}
echo "Forecast generated";
}

How to call and view an array in a function

I'm new to PHP and Kohana.
I would like to know how to call an array in a function.
I'm having the variable $productlist and I would like to add more elements into it with a function.
public $productlist = array();
public function action_index()
{
$product = new Product("Laptop","HP4897");
$product2 = new Product("TV","Samsung 8773");
$productlist[] = product;
$productlist[] = product2;
$this->add_product_to_array("Ebook","Everything you want to know");
$this->show_productlist();
}
public function add_product_to_array($product_name, $product_description)
{
$newproduct = new Product($product_name, $product_description);
array_push($productlist,$newproduct);
}
public function show_productlist(){
foreach($productlist as $key => $value)
{
print_r($value->get_product_name().'</br>');
}
}
and this is the exception i'm getting:
*ErrorException [ Warning ]: array_push() expects parameter 1 to be array, null given*
if I'm adding foreach($this->productlist as $key => $value), it tells me it can't find productlist.
Product.php
class Product {
private $_product_name;
private $_product_description;
function __construct($name,$description)
{
$this->_product_name = $name;
$this->_product_description = $description;
}
public function get_product_name()
{
return $this->_product_name;
}
//etc
PHP Classes and Objects - The Basics
Inside the class when you access the $productlist array you need to use $this->productlist. You seem to have known this in the Product class. What happened?

PHP - mysql_fetch_object with class name not working

I am trying to build a custom ActiveRecord class and am trying to return MySQL results in an object. The object will be the model.
Here's what I'm doing:
while($object = mysql_fetch_object($result, $this->_model)) {
foreach($object as $key => $val) {
if($this->is_serialized($val)) $object->$key = unserialize($val);
}
$return_value[] = $object;
}
If I do a print_r() on the result, I get an empty class (no variables have been set or anything).
Here is my model:
class User extends ActiveRecord {
public $_hasOne = "Profile";
public $_required = array('full_name', 'user_name', 'password', 'country');
public $_unique = array('full_name', 'user_name');
}
I can't figure out what I'm doing wrong!
EDIT: Fixed it in the end. At the beginning of my Activerecord class I had this:
$fields = $this->query("SHOW COLUMNS FROM " . $this->_table);
while($field = mysql_fetch_assoc($fields)) {
$this->_columns[] = $field['Field'];
$this->$field['Field'] = null;
}
Which was setting all the values to NULL!
Bit of a silly mistake. It's now:
$fields = $this->query("SHOW COLUMNS FROM " . $this->_table);
while($field = mysql_fetch_assoc($fields)) {
$this->_columns[] = $field['Field'];
if(!isset($this->$field['Field'])) $this->$field['Field'] = null;
}
Stupid question, but $this->_model is "User" right (I'd echo that value, it might have gotten unset somehow).
After that, your class should have fields by the same names as the columns which you want to represent. So:
class Foo
{
private $id;
public $val;
public function __toString(){ return "$this->id => $this->val"; }
}
mysql_connect('localhost','root','');
$q = mysql_query('SELECT 1 as id, 2 as val FROM DUAL');
$foo = mysql_fetch_object( $q, 'Foo' );
echo $foo; // 1 => 2
Next, you can't iterate over an object. You need to iterate over object properties:
foreach(get_object_vars($object) as $key => $val) {
if($this->is_serialized($val)) $object->$key = unserialize($val);
}

Object Oriented PHP Arrays

I've never tried OO PHP before so I decided to make a simple CMS to learn more. I am having a problem loading values into a multi-dimensional array.
class Article {
private $index = 0;
private $article;
public function Article() {
$get_articles = mysql_query("SELECT * FROM `articles`");
while ($result = mysql_fetch_array($get_articles)) {
echo $result["article"];
$this->article[$index]["Tags"] = $result["tags"];
$this->article[$index]["Categories"] = $result["categories"];
$this->article[$index]["Date"] = $result["date"];
$this->article[$index]["Article"] = $result["article"];
$this->article[$index]["URL"] = $result["url"];
$index++;
}
}
public function getArticle($articleID) {
return $this->article[$articleID]["Article"];
}
public function getTags($articleNumber) {
}
public function getCategories($articleNumber) {
}
public function getDate($articleNumber) {
}
}
The line echo $result["article"] outputs the one and only article value just fine, but apparently doesn't put it into the array?
$art = new Article();
echo $art->getArticle(0);
This doesn't output the article however. Would someone so kindly point out my noob mistake?
You didn't initialize your array.
$this->article = array();
while ($result = mysql_fetch_array($get_articles)) {
$this->article[$index] = array();
You probably should define your $index variable before using it in the loop. Maybe set it to the primary key field you retrieved from your query.
<?php
$index = $result['id'];
$this->article[$index]['tags'] = ...
You also need to initialize the $article member variable.
<?php
class Article {
private $article = array();
Remember that you define member variables within a class to be referenced via $this-> so you also don't need to define private $index = 0; in your class definition. Just define it inside the method.
You'll notice you used $this->article but not $this->index if you want to keep track of the length for the life of the object you'll need to replace $index with $this->index

Categories