Hi,
I am going to implement the Oops conecpt in php .So i written the below program it did not printing the values.Can any one say why this value is not printing .

class simpleclass{
		echo "Hai how are you i am fine";		
		
	}

Thank you,

With Regards,
Premnath.M

Dani AI

Generated

PHP will not execute a bare statement (like echo) directly inside a class body. The class body may declare properties, constants and methods only — putting echo there produces a parse error (for example: “Parse error: syntax error, unexpected 'echo' (T_ECHO) …”). That’s why ’s snippet didn’t print anything. As hinted, move the work into a method or the constructor, or call a static method.

A simple pattern that keeps logic and output clear:

<?php
class Greeting {
    public $message = 'Hai how are you i am fine';

    // return when you want the caller to decide when/how to print
    public function getMessage() {
        return $this->message;
    }

    // or echo from inside when you want the object to output itself
    public function show() {
        echo $this->message;
    }
}

$g = new Greeting();
echo $g->getMessage(); // caller-controlled output
// or
$g->show();            // object-controlled output

Troubleshooting tips

  • If you see a parse error pointing at echo, check for stray executable code inside a class.
  • Prefer returning values from methods when possible (better separation of logic and presentation). Use show() or a constructor (__construct) only when the class should perform I/O at instantiation.
  • If you need class-level behavior without instantiating, use a static method and call ClassName::method().

Good point from : if OOP is new, a short PHP OOP tutorial or chapter will make these rules and patterns clearer and save time.

Recommended Answers

All 3 Replies

No, you need some code like this to do hello world

<?php
class SimpleClass {
    
    function text() {
        echo "Hello World";
    }
}

$mytext = new SimpleClass();
echo $mytext->text();
?>

hi ,
Is it possible to display the values inside the class alone.If not why?

Thanks

Member Avatar for Member #120589

Have you got a tutorial on OOP? Better still buy a book. Not giving you the brush off, but you could find this info from a basic php tutorial.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.