Santa Cruz Web Factory - Products Menu

Santa Cruz Web Factory - Do You Want A Website? ... Or Do You Want A Web Blaster!!!Personal Site - Photo Site - Business Site - Custom Site - Game Site - Facebook Interface Application or Game - Custom Java Desktop Program or Application - Random Web ...Thing - Home and Small Office Network Setup and Cabling - Arbitrary Software You Design For Yourself (you design it, we create it for you) - Chrome Extensions - ...... tired of getting 'logged out?'......Their page just doesn't cut it? SCWF can help fix web pages you need to use more effectively.
                Screenshot of several programs in use - Account Blaster and some appraisal software, all created by Arlon / Santa Cruz Web Factory            Inquire          More Examples:

Introducing M Construction Corporation, Santa Cruz, Owned by Marvin Valle 831-325-3166

Introducing M Construction Corporation, Santa Cruz, Owned by Marvin Valle 831-325-3166
M Construction Corporation, Santa Cruz, Owned by Marvin Valle 831-325-3166M Construction Corporation, Santa Cruz, Owned by Marvin Valle 831-325-3166

Hierarchical Programming in C Using Nested Structs and Function Pointers

Hierarchical Programming in C Using Nested Structs and Function Pointers

By Arlon Arriola – Santa Cruz Web Factory

Welcome to my take on how you can write hierarchically structured programs in pure C, even without classes or native inner classes like in Java. I built this framework early in my systems programming course (CST 334) to test what was possible using only function pointers and nested structs.

It’s a C-style hierarchy: struct t6 defines the program structure, and struct t6 t5 instantiates and runs it. I wanted something Java-like — logical, readable, extensible. Something that encourages organized thinking and clean growth from the start. Otherwise, C projects can devolve into spaghetti code fast.

Why this structure?

I read many threads that said you “can’t define functions inside structs” in C, and that’s technically true — but only if you're thinking like a C++ or Java dev. C lets you assign function pointers to structs, and if you're clever with GCC’s statement expressions, you can build what feels like a class hierarchy.

Here’s what I found and how it led me to this paradigm:

None of the above gave me the structure I was after — but they gave me the pieces. I put them together.

Example: My Struct-Based Framework in C

Below is the full source code of my implementation. It builds a multi-level, fully nestable C framework using struct nesting and inline function pointer initialization.

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int program() {
    struct t6 {
        int (*add)(int, int);
        struct inner0 {} inner0_0;
        struct inner1 {} inner0_1;
        struct inner2 {
            struct inner3 {} inner0_3;
            struct codeFights {
                struct cF0 {
                    int (*add)(int, int);
                    int (*centuryFromYear)(int);
                    int (*checkPalindrome)(char *);
                } cF00;
            } codeFights_0;
            struct colors {
                struct console {
                    struct gnulinux {
                        struct ansi {
                            char * (*color)(int);
                            char * (*random)(int);
                            char * (*randomFG)();
                            char * (*randomBG)();
                            char * (*reset)();
                        } ansi;
                    } gnulinux;
                } console;
            } colors;
        } inner0_2;
        struct program {
            struct data {} data;
            struct state {} state;
            struct api {
                struct tricks {
                    struct codeFights2 {
                        int (*adjacentElementsProduct)(int *, int);
                    } codeFights2;
                } tricks;
                struct mo {
                    int (*zero)();
                    int (*one)();
                    int (*two)();
                } mo;
            } api;
            struct init {
                int (*zero)();
            } init;
        } program;
    };

    struct t6 t5 = {
        ({ int f(int x, int y) { return x + y; } f; }),
        {},
        {},
        {
            {},
            {
                {
                    ({ int f(int x, int y) { return x + y; } f; }),
                    ({ int f(int year) { return 1 + (year - 1)/100; } f; }),
                    ({ int f(char *inputString) {
                        for (int i = 0; i < strlen(inputString)/2; i++) {
                            if (inputString[i] != 
                                 inputString[strlen(inputString)-1-i])
                                       return 0;
                        }
                        return 1;
                    } f; })
                }
            },
            {
                {
                    {
                        {
                            ({
                                char * f(int color) {
                                    static char buf[32];
                                    snprintf(buf, sizeof(buf), "\033[0;%dm", color);
                                    return buf;
                                } f;
                            }),
                            ({
                                char * f(int bg) {
                                    time_t t; srand((unsigned)time(&t));
                                    int base = bg ? 40 : 30;
                                    int c = base + (rand() % 8);
                                    static char buf[32];
                                    snprintf(buf, sizeof(buf), "\033[0;%dm", c);
                                    return buf;
                                } f;
                            }),
                            ({
                                char * f() { return 
                                   t5.inner0_2.colors.console.gnulinux.ansi.random(0); } f;
                            }),
                            ({
                                char * f() { return 
                                    t5.inner0_2.colors.console.gnulinux.ansi.random(1); } f;
                            }),
                            ({
                                char * f() {
                                    static char buf[8];
                                    snprintf(buf, sizeof(buf), "\033[0m");
                                    return buf;
                                } f;
                            })
                        }
                    }
                }
            }
        },
        {
            {},
            {},
            {
                {
                    {
                        ({
                            int f(int *arr, int len) {
                                int max = arr[0] * arr[1];
                                for (int i = 1; i < len - 1; i++) {
                                    int prod = arr[i] * arr[i+1];
                                    if (prod > max) max = prod;
                                }
                                return max;
                            } f;
                        })
                    }
                },
                {
                    ({
                        int f() {
                            struct t4 { int (*add)(int, int); };
                            struct t4 t = ({ int f(int x, int y) { return x + y; } f; });
                            printf("Add: %d\n", t.add(1, 2));
                            return 1;
                        } f;
                    }),
                    ({
                        int f() {
                            printf("Century from 2021: %d\n"
                                 , t5.inner0_2.codeFights_0.cF00.centuryFromYear(2021));
                            printf("Is 'abba' a palindrome? %d\n"
                                 , t5.inner0_2.codeFights_0.cF00.checkPalindrome(\"abba\"));
                            return 1;
                        } f;
                    }),
                    ({
                        int f() {
                            return 1;
                        } f;
                    })
                }
            },
            {
                ({
                    int f() {
                        t5.program.api.mo.one();
                        return 1;
                    } f;
                })
            }
        }
    };

    t5.program.init.zero();
    return 0;
}

int main() {
    program();
    return 0;
}

Final Thoughts

This structure was primarily an experiment — to see how far I could push plain C into an organized, hierarchical paradigm. While it does rely on GNU extensions (statement expressions), it compiles and runs cleanly, and it’s intuitive if you're coming from object-oriented backgrounds.

That said, I’m not a C expert — I built this for learning, exploration, and potential future use. So if you do choose to build off it, please test thoroughly for memory safety, especially with more complex pointer logic or dynamic memory.

If you're curious about where I used this or how it came to be, check out the project and related writing here:

https://arlonarriola.com/?school/csumb/ilp/cst-334

— Arlon Arriola


Please also see: Stack Overflow: Can I define a function inside a C structure?

Inner Class Simulation in PHP with Nested Anonymous Objects and Closures

Emulating Inner Classes in PHP Using Closures and Anonymous Objects

By Arlon Arriola

While PHP doesn’t support true nested or inner classes, it’s possible to simulate them cleanly using a combination of (object)[...] and closure functions. This approach enables modular, inner-structured behavior — much like inner classes or nested objects in other languages — using nothing more than native PHP 7 syntax.

Working Pattern

The pattern revolves around defining inner “objects” inside the constructor of the main class using PHP's anonymous object syntax. Closures are used to retain access to the parent object context, allowing internal referencing across nested layers.

class User {
  public $id;
  public $name;
  public $password;
  public $Profile;
  public $History;

  public function __construct($id, $name, $password) {
    $this->id = $id;
    $this->name = $name;
    $this->password = $password;

    $this->Profile = (object)[
      'get' => function() {
        return 'Name: ' . $this->name . '' . (($this->History->get)());
      }
    ];

    $this->History = (object)[
      'get' => function() {
        return ' History: ' . (($this->History->track)());
      },
      'track' => function() {
        return (lcg_value() > 0.5 ? 'good' : 'bad');
      }
    ];
  }
}

echo ((new User(0, 'Anonymous', 'password'))->Profile->get)();

Output (example):

Name: Anonymous History: good

Why This Works

  • Closures capture context: Inner functions retain access to $this from the outer class.
  • No special syntax needed: All objects are created using (object)[...], avoiding class definitions entirely.
  • Safe in PHP 7+: Tested successfully in PHP 7.1.33 — no syntax errors, no reflection, no hacks.

This is an elegant workaround to PHP’s lack of true inner class syntax — keeping the logic encapsulated inside the class without requiring separate files or scaffolding.

Deeper Nesting: Multi-Level Inner Objects

This model scales — you can nest as deeply as needed by building object trees. Here’s an example with four levels of nesting:

class InnerDemo {
  public function __construct() {
    $this->Writing = (object)[
      'Files' => (object)[
        'ThirdLevel' => (object)[
          'FourthLevel' => (object)[
            'write' => function($_what, $_where, $_append) {
              $Handle = $_append ? fopen($_where, 'a') : fopen($_where, 'w');
              fwrite($Handle, $_what);
              fclose($Handle);
            }
          ]
        ]
      ]
    ];
  }
}

((new InnerDemo())->Writing->Files->ThirdLevel->FourthLevel->
      write)('Four levels of inner classes!', 'tester.html', true);

This will append the string Four levels of inner classes! to a file named tester.html.

Use Cases

  • Simulating nested services or domain layers
  • Encapsulating complex behavior inside structured trees
  • Building inline, lightweight service containers
  • Organizing logic by responsibility without creating full class hierarchies

Conclusion

This is a lightweight, expressive way to build nested behaviors in PHP. You get the benefits of inner class-style encapsulation, functional closures, and object references — all without leaving the class context or writing separate files.

Perfect for developers who want modular structure without OOP boilerplate. This technique embraces PHP’s strengths, bypasses its limitations, and keeps everything neatly scoped.


For further discussion and context, please also see the original Stack Overflow thread:
Nested or Inner Class in PHP (stackoverflow.com)

Posted by Arlon Arriola · Santa Cruz Web Factory

Functional APIs in MATLAB with Self-Referential Structs and Closure Rebinding

A modern, functional approach to building extensible APIs in MATLAB without OOP boilerplate or nested function clutter.

By Arlon Arriola



Introduction

MATLAB isn't known for its flexibility in functional programming or recursive design patterns. But with a little creativity -- and an understanding of closures, struct behavior, and variable scope -- we can build a self-referential API structure that behaves like modern web or middleware architectures.

This pattern is simple, powerful, and surprisingly underused.

I'll walk through building a multi-level API using:

  • Self-referential anonymous functions
  • Structs with recursive function calls
  • A rebinding loop that stabilizes closures across nested levels

The result? A PHP-style callable API object, built entirely in vanilla MATLAB.

Why Would You Want This?

You may want to:

  • Build a modular, extensible toolbox without lots of m files
  • Simulate middleware or route handlers
  • Encapsulate logic in a structure that behaves like an object or service container
  • Avoid OOP boilerplate when you don't need inheritance or properties
  • Stay in a purely script/function-file domain (no classes)

This design mimics associative arrays + closures in PHP or object method chains in JavaScript -- using only struct and @() in MATLAB.

The Pattern: Closure-Stabilized API Struct

api = '';  % Predeclare (not strictly necessary, but good practice)
for i = 1:3
    api = struct( ...
        'a', struct( ...
            'b', struct( ...
                'f1', @(x) disp(['f1: ', x]) ...
            ), ...
            'c', struct( ...
                'f2', @(x) api.a.b.f1(['f2 (-> f1): ', x]) ...
            ), ...
            'd', struct( ...
                'f3', @(x) api.a.c.f2(['f3 (-> f2 -> f1): ', x]) ...
            ) ...
        ) ...
    );
end

Why the for loop?

Because MATLAB closures capture by reference, not by value, we need to rebuild the full struct several times to stabilize all nested references.

Each pass:

  • Rebinds api to include more complete versions of itself
  • Updates all function handles to point to the final, stable API

We only need as many iterations as the deepest level of self-reference, so for i=1:3 handles 3 levels (f3 -> f2 -> f1). You can always set it to 10 or more and never worry.

Usage

api.a.b.f1('Hello World');   % Direct call
api.a.c.f2('Hello World');   % f2 calls f1 internally
api.a.d.f3('Hello World');   % f3 -> f2 -> f1

Output:

f1: Hello World
f1: f2 (-> f1): Hello World
f1: f2 (-> f1): f3 (-> f2 -> f1): Hello World

Each level wraps the previous one -- a perfect model for chaining behavior or composing logic.

Design Inspiration

This approach mirrors functional paradigms:

ConceptEquivalent
api.a.b.f1()PHP-style associative arrays with callable values
Recursive struct rebindingFixed-point combinator / Y-combinator
@() closuresAnonymous functions with lexical scoping
Chainable APIMiddleware stacks, command patterns, services

It's like building a small internal DSL (domain-specific language) for your code.

Use Cases

  • Command router for a CLI toolbox
  • GUI event handler API (api.ui.buttons.save.click(...))
  • Dependency injection container
  • Composable simulations (api.sim.engine.step(...))
  • HTTP-style route dispatchers (api.http.get.users(...))

You could even expand this with:

  • Auto-generated docs
  • Runtime introspection
  • Dynamic module loading
  • Middleware-like pipelines

Purpose

This tiny idiom -- rebuilding a struct of self-referential anonymous functions -- opens a door to functional design in MATLAB without the rigidity of OOP or class definitions.

The simplicity is deceptive. It gives you:

  • Namespacing
  • Closure binding
  • Call chaining
  • Function encapsulation

All in one object.

Bonus: Expandability Template

for i = 1:10  % deeper loop = deeper nesting
    api = struct( ...
        'layer1', struct( ...
            'f', @(x) disp(x) ...
        ), ...
        'layer2', struct( ...
            'f', @(x) api.layer1.f(['-> ', x]) ...
        ), ...
        'layer3', struct( ...
            'f', @(x) api.layer2.f(['-> ', x]) ...
        ) ...
    );
end

Functional Multi-Line Anonymous Functions via Recursive Self-Reference

MATLAB famously limits anonymous functions to a single expression -- no sequential logic, no if/else, no multiple statements. But that restriction can be bypassed using recursive functional programming and state threading.

The Core Trick

  • Start with a recursive anonymous function
  • Use a branching function (like a custom ternary or an if_)
  • Mutate parameters via new struct on each pass
  • Final recursion returns result

Method 1: if_ Branching with Recursion

if_ = @( pred_, cond_ ) cond_{ 2 - pred_ }();  % Choose branch

makeZ = @(makeZ, x) ...
    if_(~isfield(x, 'i'), ...
        {@() makeZ(makeZ, struct('i', 1, 'x', x, 'z', zeros(5))), ...
         @() if_(x.i == 1, ...
            {@() makeZ(makeZ, struct('i', 0, 'x', x.x, ...
                'z', [x.x(1)*cos(x.x(2)) x.z(1,2:5); x.z(2:5,:)]))}, ...
            {@() [x.z(1:2,:); x.z(3,1:3) log(x.x(3)) x.z(3,5); x.z(4:5,:)]}) ...
        });

mkZ = @(x) makeZ(makeZ, x);
mkZ([2 3 4]);

Method 2: iif and recur Pattern

iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();
recur = @(f, varargin) f(f, varargin{:});

makeZ_2 = @(x) recur(@(f, k) ...
    iif(~isfield(k,'i'), ...
        @() f(f, struct('i',1,'x',k,'z',zeros(5))), ...
        (isfield(k,'i') && k.i==1), ...
        @() f(f, struct('i',0,'x',k.x,'z',[k.x(1)*cos(k.x(2)) k.z(1,2:5); k.z(2:5,:)])), ...
        true, ...
        @() [k.z(1:2,:); k.z(3,1:3) log(k.x(3)) k.z(3,5); k.z(4:5,:)]) ...
    , x);

makeZ_2([2 3 4]);

Method 3: Custom ternary Operator

ternary = @(varargin) varargin{length(varargin) - varargin{1}};

makeZ_3 = @(makeZ_3, x) ...
    feval(ternary(~isfield(x,'i'), ...
        @() makeZ_3(makeZ_3, struct('i', 1, 'x', x, 'z', zeros(5))), ...
        @() feval(ternary(x.i==1, ...
            @() makeZ_3(makeZ_3, struct('i', 0, 'x', x.x, ...
                'z', [x.x(1)*cos(x.x(2)) x.z(1,2:5); x.z(2:5,:)])), ...
            @() [x.z(1:2,:); x.z(3,1:3) log(x.x(3)) x.z(3,5); x.z(4:5,:)]) ...
        ));

mkZ_3 = @(x) makeZ_3(makeZ_3, x);
mkZ_3([2 3 4]);

How This Works

  • State is threaded through each recursive call
  • Branching logic decides which transformation to apply
  • The function emulates a multi-line block

Why This Matters

This isn't just a MATLAB trick. It's a functional programming pattern, adapted to a language that doesn't quite support it. These methods:

  • Enable multi-line logic in inline definitions
  • Keep all code within a closure, no external state
  • Are reusable, composable, and embeddable in factory patterns

Also see: Is it possible to write several statements into an anonymous function?

Postscript: Naming the Pattern

Internally, I've started calling this structure the Closure-Stabilized API Blaster — a nod to both its recursive closure rebinding pattern and its power as a functional API generator in plain MATLAB. It's part of the broader Blaster family: minimal, modular tools that skip the boilerplate and go straight to the logic.

You can think of it as a small internal DSL builder, middleware router, or a MATLAB-native service container — all without writing a single classdef file.

Dolls By Jessie

Please Welcome Dolls By Jessie - DollsByJessie.com

Antique Dolls

Stirring Is the New Bogging

The latest trend in food appreciation is to never stir it, says web-dev extraordinaire Arlon Arriola. The reason, he says, is that stirring is lame. He cites James Bond, as well as East Asian tradition to back up his claim, see this Quora article:https://www.quora.com/East-Asians-typically-dont-mix-their-food-The-side-dishes-are-placed-on-top-of-rice-and-eaten-between-bits-of-rice-and-soup-Is-there-a-reason-why-they-dont-stir-in-the-different-toppings-and-eat-them-together-Just

In addition, he says, stirring is just lame. And this goes quadruply so, he says, for the chef. If anyone is going to do any stirring, he says, it should be the person eating the food. But still, even then, he says, seriously, why stir it, when you could just eat it, get on with it, and stop playing with your food.

This all began for him, one day, he says, when he was watching a would-be chef attempt to prepare a meal that he was to partake in. "They just wouldn't stop stirring it" he says, which eventually led him to the realization that - nobody needs to stir anything, ever! To this day, Arlon is an enormous proponent of preparation of food sans any type of stirring. "It's so easy to go overboard and just keep stirring" he says, "Tossing's fine, whirling, sliding it around - just, anything but stirring."

Sometimes you really need to turn the food over to balance the heat absorption - so, toss it, flip it, anything but stir." he says "If you start stirring it" he says "you won't be able to stop, at any logical point." He reiterates thusly - "If you look down, while you're cooking, and see your hand stirring the food all around" he says "ask yourself - 'Why, why am I doing this? Why am I doing this to myself?! Why, when I could just toss it once, or twice, instead, and then just get over myself? Why am I being so lame? Why am I stirring?' Don't do it! Stir only if you want to bog."

Welcome WebBlaster.US new ad for Santa Cruz Web Factory

Welcome WebBlaster.US new ad for Santa Cruz Web Factory

Introducing OpalCliffTrading.com - Bro Deals since 2001

OpalCliffTrading - Bro Deals since 2001
Introducing
OpalCliffTrading.com

Introducing Young's Painting Santa Cruz, Owned by Nick Young 831-854-8437

Introducing
Young's Painting Santa Cruz, Owned by Nick Young 831-854-8437
Young's Painting Santa Cruz, Owned by Nick Young 831-854-8437

Introducing Super Bomb Reversi Discussion

Introducing ZuluK.com - The Lamest Place in Cyberspace

ZuluK.com - The Lamest Place in Cyberspace
Introducing
ZuluK.com

Tags: 

Introducing Santa Cruz Abalone Works

Introducing Santa Cruz Abalone Works
Santa Cruz Abalone Works, Abalone Art, Abalone Jewelry, Fine Art, Fine Jewelry
Introducing
Santa Cruz Abalone WorksSanta Cruz Abalone Works

Introducing MoneyBlast.US

Introducing
$MoneyBlast.US$!

Introducing PleasurePointSkateboards.com

Introducing PleasurePointSkateboards.com

Introducing Damon's Cheapsk8s.com

Introducing Damon's Cheapsk8s.com

Introducing MoneyBlast.ME

Introducing
$MoneyBlast.ME$!

Introducing AccountBlaster

Introducing
AccountBlaster

Introducing Super Bomb Reversi

Introducing
Super Bomb Reversi

Introducing Arlon Arriola.com

Introducing
Arlon Arriola.com Home of Inventor Programmer Appraiser Arlon Arriola

Welcome to Santa Cruz Appraisal Factory.com

Introducing
Santa Cruz Appraisal Factory.com - Fast Santa Cruz Residential Real Estate Appraisals

Introducing Super Bomb Reversi Discussion

Base Pricing - Bro Deals

Base price is basically $25/hr labor $25/month maintenance, $25/hr labor extended development.

Example: To develop a website that would take 1 week costs $1000. 8hrs/day x 5 days x $25/hr and costs $25/month to keep up with basic maintenance.
If a half a day's work is required to add a feature that's around $100.

$25/yr to manage any domain name and that comes with email per site.

Everything's $25 basically.

Of course you do not have to pay for anything you do not like - design is essentially free - to a degree - if extended development is necessary this would be included in the fee.
In other words if re-design is due to indecision the fee for re-design has to be included.
You will get lots of choices to pick from as a basic package - but if you need more than lots - it will be included in the fee.

A basic static 'Web Page' with company or personal info and a few personal touches would take about a half a day or so, so a good estimate for a simple basic company page would be about $300 for a basic 1-3 page intro site, (not including the domain name).

- Bare Bones - Bottom Dollar -
If $300 is still too much, and only a very basic bare-bones starter intro landing page with a photo and contact info or something similar is necessary, bones starter landing site is $225 plus $25 domain name, $25/month maintenance. If a landing page is really all that is necessary and absolutely no changes are needed for periods of six months or more, the maintenance fee will be reduced to only $20/month!!

Nobody else charges these ridiculously low rates! Talk about a 'Bro Deal'!!

Subscribe to Santa Cruz Web Factory RSS