0

Why can I not do something like the following when I know that the property of myobject is going to be declared already:

define('title','boats');

myobject->title;

but this works:

myobject->boats

Is this even good practice?

2 Answers 2

3

You can't use

$myobject->title

as this is attempting to access the title property of your object. If this property does not exist, an error will be triggered.

You can use

$myobject->{title}

but I'd rather see you use a variable instead of a constant, eg

$title = 'boats';
echo $myobject->$title;

Ideally, you will know which property you want to access and use its name appropriately

$myobject->boats
Sign up to request clarification or add additional context in comments.

Comments

1

Why can I not do something like the following when I know that the property of myobject is going to be declared already:

Probably because PHP expects you to call it with a method name. There are options, though:

<?php
define( 'METHOD', 'bar' );

class Foo {
    public function bar( ) {
        echo "Foo->bar( ) called.\n";
    }
}

$foo = new Foo;
call_user_func( array( $foo, METHOD ) );

// or
$method = METHOD;
$foo->$method( );

EDIT: Ah, I seem to have misunderstood. My version is for calling methods of which the name is defined in a constant, whereas you were looking for a way of calling properties. Well, I'll leave it in here for future reference anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.