use Risan\Sentiment\Result;
final readonly class Result implements JsonSerializable is what Sentiment::analyze() and Analyzer::analyze() return. Its properties are read-only, so a result can be passed around and cached safely. You normally never construct one yourself.
$result = Sentiment::analyze('VADER is smart, handsome, and funny.');
$result->label; // Label::Positive
$result->compound; // 0.8316
$result->positive; // 0.746
$result->negative; // 0.0
$result->neutral; // 0.254
Properties
| Property | Type | Range | Description |
|---|---|---|---|
$label |
Label |
The verdict, derived from compound and the analyzer’s threshold. |
|
$compound |
float |
-1 to 1 | Overall score, rounded to 4 decimals. Negative means negative sentiment. |
$positive |
float |
0 to 1 | Share of positive signal, rounded to 3 decimals. |
$negative |
float |
0 to 1 | Share of negative signal, rounded to 3 decimals. |
$neutral |
float |
0 to 1 | Share of neutral content, rounded to 3 decimals. |
positive, negative and neutral add up to about 1. Empty text gives 0.0 for the compound and all three ratios. See Understanding the scores.
Methods
isPositive()
public function isPositive(): bool
True when $label is Label::Positive.
isNegative()
public function isNegative(): bool
True when $label is Label::Negative.
isNeutral()
public function isNeutral(): bool
True when $label is Label::Neutral.
$result = Sentiment::analyze('VADER is smart, handsome, and funny.');
$result->isPositive(); // true
$result->isNegative(); // false
$result->isNeutral(); // false
toArray()
public function toArray(): array
Returns the result as a plain array. The label is its string value.
$result->toArray();
// [
// 'label' => 'positive',
// 'compound' => 0.8316,
// 'positive' => 0.746,
// 'negative' => 0.0,
// 'neutral' => 0.254,
// ]
jsonSerialize()
public function jsonSerialize(): array
Called by json_encode(). It returns the same shape as toArray(), so you can encode a result directly.
echo json_encode($result);
// {"label":"positive","compound":0.8316,"positive":0.746,"negative":0,"neutral":0.254}
PHP drops the trailing .0 of whole floats in JSON, so 0.0 is encoded as 0. Pass JSON_PRESERVE_ZERO_FRACTION if you want 0.0.