Question about PHP syntax

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Dreamboy
Forum Newbie
Posts: 2
Joined: Mon Jun 01, 2009 6:07 am

Question about PHP syntax

Post by Dreamboy »

Hi all!

I'm totally new to PHP and I'm starting to learn it. I've been programing with ASP an other languanges for some time, but there're some things in PHP that are new to me and I'm a little confused.

I've seen some code examples were I can see this "->" or "=>". I've not seen this in any other programming languages and I'm not sure how it works. I've found it mainly when working with arrays.

Can somebody explain me how this works? Thanks!
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: Question about PHP syntax

Post by Mark Baker »

Dreamboy wrote:I've seen some code examples were I can see this "->" or "=>". I've not seen this in any other programming languages and I'm not sure how it works. I've found it mainly when working with arrays.
You'll see => when working with arrays, -> when working with objects.

=> is an array assignment operator (for want of a better description) that allows you to specify the value associated with a particular key.

Code: Select all

$myArray = array(1 => 'one', 2 => 'two')
This creates an array with two entries. The first entry has a key of 1 and a value of 'one', etc.

-> is used to access the properties or methods of an object

Code: Select all

 
class myClass {
   public $classAttribute = 'value';
 
   public classMethod($value=null) {
      $this->classAttribute = $value
   }
}
 
$myObject = new myClass();
$myObject->classMethod('result');
echo $myObject->classAttribute;
 
Dreamboy
Forum Newbie
Posts: 2
Joined: Mon Jun 01, 2009 6:07 am

Re: Question about PHP syntax

Post by Dreamboy »

Hi Mark!

Thanks for your excelent and clear explanation.

Now I know that => is used to assign values to the array (a very nice and logical way to do this) and -> is used to acces properties of methods. This is the same as the "dot" syntax in other programming languanges. I've found it also logical, but maybe is a little harder to write the -> than the "."

One more lesson to go! :)
Post Reply