I need to initialize an array of objects in PHP.
Presently I have the following code:
$comment = array();
And when i am adding an element to the array
public function addComment($c){
array_push($this->comment,$c);
}
Here, $c is an object of class Comment.
But when I try to access an functions of that class using $comment, I get the following error:
Fatal error: Call to a member function
getCommentString() on a non-object
Can anyone tell me how to initialize an array of objects in php?
Thanks
Sharmi
$this->comment = array();
Looks like a scope problem to me.
If $comments is a member of a class, calling $comments inside a function of that class will not actually use the member, but rather use an instance of $comments belonging to the scope of the function.
If other words, if you are trying to use a class member, do $this->comments, not just $comments.
class foo
{
private $bar;
function add_to_bar($param)
{
// Adds to a $bar that exists solely inside this
// add_to_bar() function.
$bar[] = $param;
// Adds to a $bar variable that belongs to the
// class, not just the add_to_bar() function.
$this->bar[] = $param;
}
}
This code might help you:
$comments = array();
$comments[] = new ObjectName(); // adds first object to the array
$comments[] = new ObjectName(); // adds second object to the array
// To access the objects you need to use the index of the array
// So you can do this:
echo $comments[0]->getCommentString(); // first object
echo $comments[1]->getCommentString(); // second object
// or loop through them
foreach ($comments as $comment) {
echo $comment->getCommentString();
}
I think your problem is either how you are adding the objects to the array (what is $this->comment referencing to?) or you may be trying to call ->getCommentString() on the array and not on the actual objects in the array.
You can see what's in the array by passing it to print_r():
print_r($comment);
Presuming you have Comment objects in there, you should be able to reference them with $comment[0]->getCommentString().
Related
How do I know if an arbitrary object has any properties in PHP?
I need it for a recursive search on JSON objects as a break condition
i.e break search when the object has no more sub-objects.
I thought of property_exists but it checks a particular property, while I want to know if any property exists.
You can use a foreach loop:
foreach (new object as $prop => $value) {
echo "property \$$prop is $value\n";
}
Also You can do it conveniently with get_object_vars:
$propertyName = key(get_object_vars($object));
The function get_object_vars() will return a list of all accessible properties on an object.
You can try to use this function:
http://php.net/manual/en/function.get-object-vars.php
From the docs:
Returns an associative array of defined object accessible non-static properties for the specified object in scope. If a property has not been assigned a value, it will be returned with a NULL value.
You can also use the ReflectionClass to get the object properties like this:
$obj = new YourObjectClass;
$reflect = new ReflectionClass($obj);
$props = $reflect->getProperties();
foreach ($props as $prop) {
print $prop->getName() . "\n";
Casting the object to an array and performing a count on the resulting array will tell you if an object has properties.
$foo = new Bah();
$propertiesAsArray = (array) $foo;
if(count($propertiesAsArray)) {
//this object has properties
} else {
//this object does not have properties
}
You could use :
if(isset($yourobject)){
//YourCode
}
in a loop to see if the object have anything already set.
I am trying to sort an array of values using a class method. The values are as follows
$agegroups = array("08","910","1112","1314","1516","1718","1999");
However, they can be any combination of numbers. The values above correspond to age groups used on my site and are are defined in a database table, so I can't hard code them. I have an object that contains an array of age group defintions like this
private $agegroups = array();
function __construct() {
// retrieve data from the database
while($data = $sth->fetch()) {
$ag = new StdClass();
$ag->low = $data['low']; //stores the low end of the age group
$ag->high = $data['high'] //stores the high end of the age group
$this->agegroups[$data['key']] = $ag;
}
}
$data['key'] corresponds to the $agegroups array defined above. In the same class, I defined a sort method
function sort($a,$b) {
$aAG = $this->agegroups[$a];
$bAG = $this->agegroups[$b];
return $aAG->low > $bAG->low ? 1 : -1;
}
My understanding is that usort can only use a static method. However my object needs to retrieve the values from a database, so I can't make it static.
I tried using an anonymous function with usort that could use an instance of the class defined outside the function but I get an error about an undefined object.
$agObj = new agegroups();
$agegroups = usort($agegroups, function($a, $b){
global $agObj;
return $agObj->sort($a,$b);
});
The error I get is Fatal error: Call to a member function sort() on a non-object
I release I can create a new instance of the object inside the anonymous function but I don't want to have to query the database each time. Is there a way to use my class to sort these values?
Wherever a function is required, you can use array(object, functionName) to call the method on that object.
usort($agegroups, array($agObj, 'sort'));
BTW, you shouldn't assign the result of usort back to agegroups. The sorting functions modify the array in place; they return a boolean, not the reordered array.
I have the following class with several properties and a method in PHP (This is simplified code).
class Member{
public $Name;
public $Family;
public function Fetch_Name(){
for($i=0;$i<10;$i++){
$this[$i]->$Name = I find the name using RegExp and return the value to be stored here;
$this[$i]->Family = I find the family using RegExp and return the value to be stored here;
}
}//function
}//class
In the function Fetch_Name(), I want to find all the names and families that is in a text file using RegExp and store them as properties of object in the form of an array. But I don't know how should I define an array of the Member. Is it logical or I should define StdClass or 2-dimension array instead of class?
I found slightly similar discussion here, but a 2 dimensional array is used instead of storing data in the object using class properties.
I think my problem is in defining the following lines of code.
$Member = new Member();
$Member->Fetch_name();
The member that I have defined is not an array. If I do define it array, still it does not work. I did this
$Member[]= new Member();
But it gives error
Fatal error: Call to a member function Fetch_name() on a non-object in
if I give $Member[0]= new Member() then I don't know how to make $Member1 or Member[2] or so forth in the Fetch_Name function. I hope my question is not complex and illogical.
Many thanks in advance
A Member object represents one member. You're trying to overload it to represent or handle many members, which doesn't really make sense. In the end you'll want to end up with an array that holds many Member instances, not the other way around:
$members = array();
for (...) {
$members[] = new Member($name, $family);
}
Most likely you don't really need your Member class to do anything really; the extraction logic should reside outside of the Member class, perhaps in an Extractor class or something similar. From the outside, your code should likely look like this:
$parser = new TextFileParser('my_file.txt');
$members = $parser->extractMembers();
I think you should have two classes :
The first one, Fetcher (or call it as you like), with your function.
The second one, Member, with the properties Name and Family.
It is not the job of a Member to fetch in your text, that's why I would make another class.
In your function, do your job, and in the loop, do this :
for($i = 0; $i < 10; ++$i){
$member = new Member();
$member->setName($name);
$member->setFamily($family);
// The following is an example, do what you want with the generated Member
$this->members[$i] = $member;
}
The problem here is that you are not using the object of type Member as array correctly. The correct format of your code would be:
class Member{
public $Name;
public $Family;
public function Fetch_Name(){
for($i=0;$i<10;$i++){
$this->Name[$i] = 'I find the name using RegExp and return the value to be stored here';
$this->Family[$i] = 'I find the family using RegExp and return the value to be stored here';
}
}
}
First, $this->Name not $this->$Name because Name is already declared as a member variable and $this->Name[$i] is the correct syntax because $this reference to the current object, it cannot be converted to array, as itself. The array must be contained in the member variable.
L.E: I might add that You are not writing your code according to PHP naming standards. This does not affect your functionality, but it is good practice to write your code in the standard way. After all, there is a purpose of having a standard.
Here you have a guide on how to do that.
And I would write your code like this:
class Member{
public $name;
public $family;
public function fetchName(){
for($i=0;$i<10;$i++){
$this->name[$i] = 'I find the name using RegExp and return the value to be stored here';
$this->family[$i] = 'I find the family using RegExp and return the value to be stored here';
}
}
}
L.E2: Seeing what you comented above, I will modify my answer like this:
So you are saying that you have an object of which values must be stored into an array, after the call. Well, after is the key word here:
Initialize your object var:
$member = new Memeber();
$memebr->fechNames();
Initialize and array in foreach
$Member = new Member();
foreach ($Member->Name as $member_name){
$array['names'][] = $member_name;
}
foreach ($Member->Family as $member_family) {
$array['family'][] = $member_family;
}
var_dump($array);
Is this more of what you wanted?
Hope it helps!
Keep on coding!
Ares.
I have a class with several variables like:
class ABC
{
$var1=0;
$var2=0;
...
}
Instead of setting variables one by one like;
$ABC=new ABC();
$ABC->var1=1;
$ABC->var2=1;
...
How to loop through all class' (instance) variables and dynamically set them all to some value.
You could use get_object_vars to get the non static properties of the object, and then loop through that.
$object_vars = get_object_vars($ABC);
foreach ($object_vars as $name => $value) {
$ABC->{$name} = $newVal;
}
See more information here: http://php.net/manual/en/function.get-object-vars.php
I can't figure this out. I've create a simple class that returns an array of arrays. Here is the class contructor...
class BlogComments {
public $commentArray=array();
public $blogId;
function __construct($inId) {
if(!empty($inId)) {
$this->blogId=$inId;
$sql="select id,name,url,comment,email from blog_comment where blog_id=$inId";
$link2=GetConnection();
$query=mysql_query($sql,$link2) or die("Invalid blog id:".mysql_error());
while($row=mysql_fetch_array($query)) {
$this->commentArray=array(
"id"=>$row['id'],
"name"=>$row['name'],
"url"=>$row['url'],
"email"=>$row['email'],
"comment"=>$row['comment']
);
}
mysql_close($link2);
}
}
}
I'm trying to access each member of the array via a loop. It's entering the loop but the values returned are empty. I've verified that data is being written into the array. Here's my code...
include "include/commentclass.php";
$comments = new BlogComments($post->id);
foreach($comments as $comment) {
echo "<h4>".$comment->commentArray['name']."</h4>
".$comment->commentArray['url']."
<p>".$comment->commentArray['comment']."</p>";
}
Basically it returns empty tags. I've also verified that $post->id holds a valid value. Any ideas what I'm doing wrong?
Thanks for the help,
B
You are doing some mistakes, the first is the one netcoder pointed out: you are using the object as an array without implementing an Iterator interface. The second is that you are assigning directly the result array to $this->commentArray. You should append the result to the array this way: $this->commentArray[] = array(
Try this:
$comments = new BlogComments($post->id);
foreach ($comments->commentArray as $comment) {
echo "<h4>".$comment['name']."</h4>
".$comment['url']."
<p>".$comment['comment']."</p>";
}
The new keyword returns a single object. Unless your object (BlogComments) implements Traversable, foreach will act on the public properties commentArray and blogId, and not on the commentArray contents.
You could also have your class implement an Iterator interface.