Jump to content

Error using print, {} and a function


ericorx

Recommended Posts

have some code that doesn't seem to work and i'm not sure why. I tried three different ways of coding it and example 1 and 2 work but the third doesn't.

I get a unexpected ( error from Example 3.

 

Is it just that I have () enclosed in {} enclosed in a print string? Is there away around this.. It just seems shorter than concatenating.

 

I have a UnitCounter class with a function called totalWeight that does is a quick calculation of units * weight and return that value. I have assigned weights and unit numbers to the vars.

 

$b = new UnitCounter;

//Example 1:  This works
print "total weight = " . $b->totalWeight() . "kg";

//Example 2:  This works
$a = $b->totalWeight();
print "total weight = {$a} kg";

//Example 3:  This doesn't work.. why?
print "total weight = {$b->totalWeight()} kg";

 

 

 

Thanks,

e

Link to comment
https://forums.phpfreaks.com/topic/73789-error-using-print-and-a-function/
Share on other sites

This works for method calls but not function calls (PHP 5.0)

 

<?php
class a {
    function  totalWeight() {return '9,999';}
}

function c()
{
    return 'xxx';
}

$b = new a;

print "total weight = {$b->totalWeight()} kg <br>";      // works --> total weight = 9,999 kg
print "total weight = {c()} kg <br>";                    // NO    --> total weight = {c()} kg 
print "total weight = " . c() . " kg <br>";              // works --> total weight = xxx kg 
  
?>	

 

EDIT: PHP 4.3.9 gives parse error on the print with method call

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.