Is there a ColdFusion equivalent to PHP for include_once?
Asked Answered
D

2

6

I've been adding this to my pages:

pagewithinclude.cfm

<cfinclude template = "_pagename.cfm">

_pagename.cfm

<cfif Not IsDefined("variables.included_pagename")>
<cfparam name = "variables.included_pagename" default = "1">

rest of page

</cfif>

Is there a better way in CF? Something similar to PHP's include_once?

Disembowel answered 25/3, 2010 at 16:59 Comment(5)
Since by definition, you will not get to the CFPARAM if the variable is defined, you can use CFSET instead. This will have less overhead.Preeminence
that's not how it works ben, on the first time the file is included, the variable has YET to be defined. If the file is included AGAIN, the variable is defined (from the first time) and the cfparam and rest of page is never reachedDisembowel
Hi David. You have a NOT IsDefined check, and then inside that, a cfparam. This means that the only time your cfparam will be reached, is if it's not already defined, making the cfparam redundant. You could use a cfset there and your code would work exactly the same.Politics
That behavior is exactly what I want, but after thinking this over, I figured out what both of you meant to say: the redundancy occurs when CFPARAM does its own check to see if a variable is defined before determining whether to set it, so a CFSET would give a little performance increase by not doing a second check for defined status.Disembowel
Since CF10 you can add runonce=trueCrossruff
M
5

Nope, what you've done is probably the best way to do it. Although I'd use a Request variable instead.

Myology answered 25/3, 2010 at 17:48 Comment(3)
why is the request scope better?Disembowel
I think request scope gets Garbage Collected faster?Jayjaycee
The request scope will be available to all calling templates, even if called by cfmodule, cfc, etc.Preeminence
C
1

This question was asked in 2010 (and many answers were then or 2011). Since then, in 2012, CF10 added the optional runOnce attribute for CFINCLUDE (or its script equivalent). Marques had added a mention of that attribute in a comment on the original question, in 2016, but it could be missed as an "answer".

I was helping someone who was seeking a solution to this problem, and I found this discussion, but noticed its lack of a clear answer. (And while there may be technicalities that distinguish CF's runonce from PHP's include_once, they are close enough in concept that it seems worth pointing out, even if it may not be the exact solution to the OP's question--if they even cared, now 10 years later.)

Cambridgeshire answered 10/10, 2022 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.