Class: PHP::Literal::Hash

Inherits:
PHP::Literal show all
Defined in:
lib/php/syntax/literal.rb

Overview

Examples:

Creating an unordered associative array from a Hash

  PHP::Literal::Hash.new(:a => 1, :b => 2, :c => 3).to_s
  #=> "array(c => 3, a => 1, b => 2)"

Creating an ordered associative array from Array pairs

  PHP::Literal::Hash.new([:a, 1], [:b, 2], [:c, 3]).to_s
  #=> "array(a => 1, b => 2, c => 3)"

See Also:

Instance Method Summary

Methods inherited from PHP::Literal

#<=>

Methods inherited from PHP::Node

#<<, #<=>, #children?, #each, #indent, #indent=, #to_s

Constructor Details

- (Hash) initialize(*pairs)

A new instance of Hash

Parameters:



80
81
82
83
84
85
86
# File 'lib/php/syntax/literal.rb', line 80

def initialize(*pairs)
  if pairs.size == 1 && pairs.first.is_a?(::Hash)
    @children = pairs.first.to_a
  else
    @children = pairs
  end
end

Instance Method Details

- (String) to_php

Returns the PHP representation of this associative array literal.

Returns:

  • (String)


92
93
94
95
# File 'lib/php/syntax/literal.rb', line 92

def to_php
  pairs = children.map { |k, v| "#{k} => #{v}" }
  "array(#{pairs.join(', ')})"
end