CFML inplementation of toString for CFCs
Asked Answered
S

1

7

In PHP I could have this situation:

<?php
class Person {

    public $firstName;
    public $lastName;

    function __construct($firstName, $lastName)
    {
        $this->firstName = $firstName;
        $this->lastName = $lastName;
    }

    function __toString()
    {
        return "{$this->firstName} {$this->lastName}";
    }
}

echo new Person("Adam", "Cameron"); // Adam Cameron

(runnable demo)

I could have sworn there was an equivalent in CFML, eg:

// Person.cfc
component {

    function init(id, firstName, lastName){
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    function toString(){
        return "#this.firstName# #this.lastName#";
    }
}

// test.cfm
writeOutput(new Person("Adam", "Cameron"));

I thought it was new to CF11 or CF2016.

But this dun't work. I know I can do customer serialisers, but that's not a good fit here.

I also know I can effect the same thing in various other ways, but that's not the question here. I am specifically asking about being able to implement a toString method or some such to just be able to specify how to represent an object as a string.

Am I mis-remembering CFML, or am I doing something wrong?

Statis answered 28/7, 2017 at 18:40 Comment(2)
My guess is mis-remembering, but then again, I still use version 9.Polygamist
@james-a-mohler I rolled-back your edit of the tags because it was a pointless change and they were inaccurate in the context of the question. I'm not asking about CF11 or CF2016, I'm asking a CFML question relating to ColdFusion's implementation of it. Hence being tagged as such.Statis
W
7

I believe you are thinking of the conversion functions implemented in Lucee...

http://docs.lucee.org/guides/Various/TIPS/TIPS-implicit-conversions.html

  • _toBoolean()
  • _toDate
  • _toNumeric
  • _toString

To the best of my knowledge, ColdFusion does not have this.

Windbreak answered 28/7, 2017 at 19:44 Comment(1)
Yup, those're them. I thought CF had caught up with that: seemingly not. Cheers!Statis

© 2022 - 2024 — McMap. All rights reserved.