May 7, 2013

Accessing Object within Array

Viablepath’s Questions:

I have the following output:

Array (
  [0] => stdClass Object (
        [id] => 20
        [news_title] => Startup finance docs in GitHub
        [news_url] => http://venturebeat.com/2013/03/06/fenwick-west-github/
        [news_root_domain] => venturebeat.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-06 11:20:03
        [news_points] => 0
    )
    [1] => stdClass Object (
        [id] => 21
        [news_title] => The problems with righteous investing
        [news_url] => http://gigaom.com/2013/03/07/the-problems-with-righteous-investing/
        [news_root_domain] => gigaom.com
        [news_category] =>
        [news_submitter] => 4
        [news_time] => 2013-03-08 09:14:17
        [news_points] => 0
    )
)

How would I access something like news_url in these? I’ve tried this, but to no avail:

print_r $this->$record[0]->news_title;

Your code is a little incomplete, and hard to follow, but try this:

 $arr =    Array();

    $obj0 = new stdClass;
    $obj0->id = 123;
    $obj0->news_title = "some title 0";
    //etc...
    $obj1 = new stdClass;
    $obj1->id = 124;
    $obj1->news_title = "some title 1";
    //etc...

   $arr[0] = $obj0;
   $arr[1] = $obj1;

    print_r($arr);

or something like

print_r($arr[0]);

or even

 echo $arr[0]->id;

You are using class property, you might want to check if it is accessible first. While accessing the class property after using $this you dont need the additional $, just use $this - record. Like

echo $this -> record[0] -> title;

If record is a valid class property which is an array and it still does not work. Give this a try too:

echo {$this -> record[0]} -> title;
April 24, 2012

php create objects from list of class files

Question by ing. Michal Hudak

I have directory CLASSES with files in my project.

../classes/class.system.php
../classes/class.database.php
...

I pull out every class and include it to main index.php with this code:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
}

and then I create (manually write) objects for example:

$system = new System();
$database = new Database();
...

Q: How can I automatically generate object for each class from list of files in directory CLASSES without writing them?

Thank you for your answers and code.

EDIT:

My working solution:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    ${$obj} = new $class();
}

Answer by ing. Michal Hudak

// load classes and create objects
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    // create object for every class
    ${$obj} = new $class();
}

Answer by Starx

IF you follow a typical pattern, while creating those files like

class.<classname>.php

Then

foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    ${strtolower($t[1])}= new ucfirst($t[1])(); // automatically create the object        

}
April 18, 2012

How can I detect if an image object is being displayed?

Question by Mark

When I load an image object in the DOM for large images this will freeze the display for a moment on the iPad.

For testing purpose, let a GIF animation loader spin and add a large image to the DOM, when the image is loaded and added to the DOM you will notice that that GIF animation will freeze until the image is being displayed. This freeze will be enough to disable the CSS3 animation effect on it.

Is there something like

var image = new Image();
image.ready = function() { alert('the image is being displayed.') };

Answer by Starx

You can check if the image has been loaded like this

var img = new Image();
img.onload = function() {
  alert('Done!');
}
img.src = '/images/myImage.jpg';
April 9, 2012

Force variable pass as object

Question by Gabriel Santos

I need to define the type of passed variable as an generic object, how?

Tried:

public function set($service = null, (object) $instance) {
    [..]
}

Can stdClass help? How?

Thanks!

Answer by zerkms

Nope, in php all classes aren’t derive from the common ancestor.

So doubtfully you can use current php’s implementation to state “object of any class”

Answer by Starx

No, the object has to be some class. You can give the any class name as object’s type

public function set($service = null, ClassName $instance) {
    //now the instance HAS to be the object of the class
}

Or a basic trick would be to create a basic class yourself

Class GenericObject {}
$myobj = new GenericObject();
$myobj -> myCustomVar = 'my custom var';

//Now send it
public function set($service = null, GenericObject $instance) {
   [...]
}
April 7, 2012

Is it possible ? "Javascript Subclass"

Question by EyeSalut

I want to know i can do something “similar” to this (not working) code in javascript ?

function Player ()     {

    this.Inventory = function ()     {

        this.Inventory.UseItem = function(item_id)    {
            /* use the item ... */
        }

    }

}

and then use it like that :

current_player = new Player();
current_player.Inventory.UseItem(4);

Answer by Starx

Yeah

function Player ()     {

    var Inventory = {


        UseItem : function(item_id)    {
            /* use the item ... */
        }

    };

}
March 9, 2012

Instantiate an variable with a methods return object

Question by Eirc man

I have been searching for hours but I can’t seem to understand why this does not work. Here is the code

My goal is to have a different method to load the XML document, and another one to print and manage that document.

class ...

//Fetch and print xml document
    function fetchFromXMLDocument($XMLDocName) {
        $xmlDoc = new DOMDocument();
        $xmlDoc->load($XMLDocName);
        return $xmlDoc;

    }

Here I want do add the value of the fetchFromXMLDocument() to my $he variable.
but it does not seem to be working?

function printXml($XMLDocName) {
   //this seems not to be right??       
    $he = fetchFromXMLDocument($XMLDocName);

    //after that this is what I want to do..
    // $items = $he->getElementsByTagName("item");
         ...
    }

Does anybody have an idea on why that might be?

Answer by Starx

The problem is that function fetchFromXMLDocument(); is inside a class.

If the method you are accessing it from printXML, is within the same class then you should access it using $this operator.

function printXml($XMLDocName) {    
     $he = $this -> fetchFromXMLDocument($XMLDocName);
     ...
}

However, If the method you are accessing it from printXML, is outside. Then first you have to create and object of the class and access it.

function printXml($XMLDocName) {    
     $obj = new yourxmlclassname();
     $he = $obj -> fetchFromXMLDocument($XMLDocName);
     ...
}
May 1, 2011

How to get records from MySQL into value objects with PHP

Question by user733284

I have this code:

$Result = DBQuery("SELECT user_id,nick_name,email FROM users LIMIT $fromindex.",".$numOfUsers);
if ($Result)
{
     $resultUsers->UersData=$Result;
}

The problem is that the results U get are in some kind of format that i don’t know.

I want to get the results in array format, which every element of that array should be a value object class of this type:

class UserVO {
    var $_explicitType="UserVO";

    var $id;

    var $nickName;

    var $email;
}

Any idea how it can be done?

Answer by Starx

My answer might not sound very helpful, regarding your unclear question. I am supposing, that the function DBquery returns the result of mysql_query(......). If thats true, then you are feeding the userData with a Resource string which is a resource data type.

There are few ways to access such resource String

  1. If the query exports multiple results

    while($row = mysql_fetch_assoc($userData) {
       print_r($row); //This is where you will get your mysql rows.
    }
    
  2. If the query return single row

    $row = mysql_fetch_assoc($userData);
    print_r($row); // //This is where you will get your mysql rows.
    

Here are some must check links

...

Please fill the form - I will response as fast as I can!