Jump to content

How is "->" used? As in, $variable->function(). Newbie here.


teraparsec

Recommended Posts

Hi everybody,

 

I am trying to teach myself PHP and have looked at many W3C tutorials but am unclear as to what a piece of syntax refers.

 

I am learning about parsing XML with the SimpleXML parser, here is a snippet of code:

 

<?php
$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
  {
  echo $child->getName() . ": " . $child . "<br />";
  }
?>

 

How is the $xml->getName() construction used?  That is, $variable->function(), what does this mean and how is it used?

 

THANKS!!!!!!

 

 

That's PHP OOP (Object Oriented Programming).

 

$variable represents an object, and function() is a method of that object. Here's an example:

 

<?php
class someClass
{
private $a;

public function someClass() // Constructor, called once a new object is made
{
	$this->a = 'Hello World';
}

public function displayA()
{
	echo $this->a;
}
}

$variable = new someClass();
$variable->displayA(); // Hello World

 

Look here There are plenty of examples.

So the line '$xml = simplexml_load_file("test.xml");' makes $xml an 'object' and functions in SimpleXML can be applied to that object because the $xml 'object' was created with the simplexml_load_file() function?  So '$xml->anysimplexmlfunction()' would work but '$xml->anyotherphpfunction()' would not?  (assuming that the data in $xml was appropriate for the function)

So the line '$xml = simplexml_load_file("test.xml");' makes $xml an 'object' and functions in SimpleXML can be applied to that object because the $xml 'object' was created with the simplexml_load_file() function?  So '$xml->anysimplexmlfunction()' would work but '$xml->anyotherphpfunction()' would not?  (assuming that the data in $xml was appropriate for the function)

Yes, that's all correct. If you wanted to preform another function on $xml you could do something like..

 

$xml = somefunction($xml);

if you are using static method

 

call method type is

self::method();

 

Extend methods are

 

<?

class a
{
public funcion asd()
{
echo "asd";
}

}

class b Extends a
{
// now b has a's methods

public function z
{
    // call asd method
    parent::asd();
}

}

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.